Java - 定义和访问注释?

时间:2012-12-27 06:49:14

标签: java annotations

我有一个名为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();
   }

}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

Andremoniy的回答绝对正确。 我唯一改变的是我在堆栈跟踪中查找的方式。

    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();
    }