gpt4 book ai didi

Java - 定义和访问注释?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:34:38 28 4
gpt4 key购买 nike

我有一个名为 Client 的抽象类。我怎样才能访问在子类的调用方法上声明的注释?处理此问题的最佳方法是什么?

public abstract class Client {

protected void synchronize() {

// How can I get the Annotation defined on inheriting class?
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StackTraceElement lastStackElement = stackTraceElements[stackTraceElements.length-1] ;
Method m = this.getClass().getMethod(lastStackElement.getMethodName(), String.class, int.class);
m.getAnnotation(Cache.class);

// synchronize data from server
}

}

.

public class OrderClient extends Client {

@Cache(minute = 5)
public void synchronizrWithCustomerId(String customerId) {

// So some stuff setup body and header

super.synchronize();
}

}

最佳答案

根据您的示例,此代码运行良好:

public class TestS1 {

public abstract class Client {

protected void synchronize() throws NoSuchMethodException {
// How can I get the Annotation defined on inheriting class?
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StackTraceElement lastStackElement = stackTraceElements[2];

//注意这里:stackTraceElements[2]

     Method m = this.getClass().getMethod(lastStackElement.getMethodName(), String.class);
Cache annotation = m.getAnnotation(Cache.class);
System.out.println("Cache.minute = " + annotation.minute());
// synchronize data from server
}
}

你还需要用@Retention(RetentionPolicy.RUNTIME)标记你的注释

    @Retention(RetentionPolicy.RUNTIME)
@interface Cache {
int minute();
}

public class OrderClient extends Client {
@Cache(minute = 5)
public void synchronizrWithCustomerId(String customerId) throws NoSuchMethodException {
// So some stuff setup body and header
super.synchronize();
}
}

public void doTest() throws NoSuchMethodException {
OrderClient oc = new OrderClient();
oc.synchronizrWithCustomerId("blabla");
}

public static void main(String[] args) throws NoSuchMethodException {
TestS1 t = new TestS1();
t.doTest();
}

}

输出是:Cache.minute = 5

关于Java - 定义和访问注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14050609/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com