Annotate anonymous inner class

后端 未结 3 1827
臣服心动
臣服心动 2021-01-07 16:37

Is there a way to annotate an anonymous inner class in Java?

In this example could you add a class level annotation to Class2?

public void method1()          


        
相关标签:
3条回答
  • 2021-01-07 16:41

    Yes, as mentioned by yegor256, it is possible, since JDK 8 adopted JSR 308 (type annotations).

    So now whenever an annotation is decorated by @Target({ElementType.TYPE_USE}), it can be used for annotating an anonymous class at runtime. For instance:

    @Target({ ElementType.TYPE_USE })
    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation {
        String value();
    }
    
    Object o = new @MyAnnotation("Hello") Object() {};
    

    The tricky part is how to access the annotation:

        Class<?> c = o.getClass();
        AnnotatedType type = c.getAnnotatedSuperclass();
        System.out.println(Arrays.toString(type.getAnnotations()));   
    
    0 讨论(0)
  • 2021-01-07 17:00

    Not yet. This feature is suggested by JSR 308, and may be included in future versions of Java.

    0 讨论(0)
  • 2021-01-07 17:01

    No. You'd need to promote it to a "proper" class. It can still be scoped within the outer class if necessary, so it doesn't need to be a top-level class, or public, or whatever. But it does need a proper class definition to attach the annotation to.

    0 讨论(0)
提交回复
热议问题