java 注释匿名内部类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3021548/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Annotate anonymous inner class
提问by Mark Pope
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() {}
  });
}
采纳答案by dty
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.
不,您需要将其提升为“适当”的课程。如有必要,它仍然可以在外部类内进行作用域,因此它不需要是顶级类、公共类或其他类。但它确实需要一个适当的类定义来附加注释。
回答by yegor256
回答by jan.supol
Yes, as mentioned by yegor256, it is possible, since JDK 8 adopted JSR 308 (type annotations).
是的,正如 yegor256 所提到的,这是可能的,因为JDK 8 采用了 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}),它就可以用于在运行时注解匿名类。例如:
@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()));   

