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()
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()));
Not yet. This feature is suggested by JSR 308, and may be included in future versions of Java.
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.