Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Defining and accessing annotations?

I have an abstract class called Client. How can I get access to an annotation that was declared on the calling method on the child class? What's 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();
   }

}
like image 905
aryaxt Avatar asked Dec 27 '12 06:12

aryaxt


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

// take attention here: 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 mark your annotation with @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 is: Cache.minute = 5

like image 110
Andremoniy Avatar answered Oct 04 '22 16:10

Andremoniy