代码之家  ›  专栏  ›  技术社区  ›  codebreaker

直接获取字段的注释

  •  0
  • codebreaker  · 技术社区  · 11 年前

    在一个类中,我有几个字段是匿名类。其中一些有注释。例如:

    public class MainClass {
    
        @Annotation
        public static Test t = new Test() {...}
    
        Interface Test {...}
    
    }
    

    我知道我可以通过执行MainClass.class.getField(“t”).getAnnotations()来查看t的注释,但有什么方法可以通过引用t来获取t的注释吗?例如,如果我有一个测试集合,我可以通过迭代来查看它们的注释吗?

    Collection<Test> c;
    ...
    // MainClass.t is in collection c
    ...
    
    for (Test test : c) {
    
        // get annotation of test
    
    }
    

    我猜这是不可能的,如果不可能,接近我想要做的事情的最佳方式是什么?

    2 回复  |  直到 11 年前
        1
  •  1
  •   Sotirios Delimanolis    11 年前

    引用只是指向一个对象,而对象没有任何注释。字段(方法、类、参数等)可以。所以,不,这是不可能的。

    接近我想要做的事情的最佳方式是什么?

    没有。

    public void someMethod() {
        Test test = MainClass.t;
        // some more
    }
    

    MainClass.t 是一个 Field .局部变量 test 就是这样,一个局部变量。

    请注意,您可以对局部变量进行注释

    public void someMethod() {
        @SomeAnnotation
        Test test;
    }
    
    @Target(value = { ElementType.LOCAL_VARIABLE })
    public @interface SomeAnnotation {
    
    }
    

    但无法检索该注释。例如,它主要由IDE使用 @SuppressWarnings .

        2
  •  1
  •   Scheintod    11 年前

    我猜 Test 是一个接口,并且您需要实现类的注释。

    for (Test test : c) {
    
        test.getClass().getField( "xx" ).getAnnotations()
    
    }
    

    当然你可以用 test.getClass().getFiels() 以获取所有字段,然后从中获取注释。这完全取决于你 真正地 想做的事。