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() { add(new Class2() { public void method3() {} }); }
Java anonymous inner class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
It can extend exactly one class and can implement multiple interfaces. It can extend exactly one class and implement exactly one interface. It can implement multiple interfaces regardless of whether it also extends a class. It can extend exactly one class or implement exactly one interface.
3.12. An anonymous class cannot define any static fields, methods, or classes, except for staticfinal constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With