Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotate anonymous inner class

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() {}   }); } 
like image 577
Mark Pope Avatar asked Jun 11 '10 09:06

Mark Pope


People also ask

How do you define anonymous inner class?

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.

Can inner class instantiate anonymously?

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.

Which is true about an anonymous inner class?

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.

Can Anonymous classes be private?

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.


1 Answers

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.

like image 101
dty Avatar answered Sep 21 '22 13:09

dty