Java Definition and access to annotations?

I have an abstract class Customer. How can I access the annotation that was declared for the call method in the child class? What is the best way to handle this?

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(); } } 
+7
source share
2 answers

Based on your example, this code works well:

 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]; 

// note: 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 } } 

also you need to tag annotation @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(); } } 

Output : Cache.minute = 5

+2
source

Andromoni's answer is absolutely correct. The only thing I changed is how I view the stack trace.

  Cache cache = null; try { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); for (StackTraceElement element : stackTraceElements) { if (this.getClass().getName().equals(element.getClassName())) { Method method = this.getClass().getMethod(element.getMethodName(), String.class); cache = method.getAnnotation(Cache.class); break; } } } catch (NoSuchMethodException e) { e.printStackTrace(); } 
0
source

All Articles