简体   繁体   English

注释匿名内部类

[英]Annotate anonymous inner class

Is there a way to annotate an anonymous inner class in Java? 有没有办法在Java中注释匿名内部类?

In this example could you add a class level annotation to Class2? 在此示例中,您可以向Class2添加类级别注释吗?

public void method1() {
  add(new Class2() {
    public void method3() {}
  });
}

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. 但它确实需要一个适当的类定义来附加注释。

Not yet. 还没。 This feature is suggested by JSR 308 , and may be included in future versions of Java. 此功能由JSR 308建议,并且可能包含在Java的未来版本中。

Yes, as mentioned by yegor256 , it is possible, since JDK 8 adopted JSR 308 (type annotations) . 是的, 正如yegor256所提到的那样 ,因为JDK 8采用了JSR 308(类型注释)

So now whenever an annotation is decorated by @Target({ElementType.TYPE_USE}) , it can be used for annotating an anonymous class at runtime. 因此,每当注释由@Target({ElementType.TYPE_USE})修饰时,它都可以用于在运行时注释匿名类。 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()));   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM