-2

Does an anonymous class get created (not instantiated, but the class actually being defined/loaded) each time its enclosing method is called or are they reused? For instance:

public MyInterface getAnonymousMyInterface() {
 return new MyInterface(){
  public void doStuff(){
   System.out.println("did stuff");
  }
 }
}

Will calling getAnonymousMyInterface() create two different classes?

vikarjramun
  • 1,042
  • 12
  • 30

2 Answers2

7

No it will not. A single class is created at compile time for the anonymous class (in the form OuterClass$1.class) and that is so the single class that is loaded by the classloader.
Then at runtime, each getAnonymousMyInterface() invocation will create a distinct instance of the MyInterface anonymous class as the new operator creates a new instance of the class declared after that.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
4

I just figured it out by running the following program:

public class Main {
 public static interface MyInterface {
  void doStuff();
 }
 public static void main(String[] args) {
  System.out.println(getAnonymousMyInterface().getClass().equals(getAnonymousMyInterface().getClass()));
 }


 public static MyInterface getAnonymousMyInterface() {
  return new MyInterface() {
   public void doStuff() {
    System.out.println("did stuff");
   }
  };
 }

This prints true so the answer is no, an anonymous class is created once, and each instance is from the same class.

vikarjramun
  • 1,042
  • 12
  • 30
  • You can also take a look at the output class files, the anonymous classes are usually named `Main$1.class`. It's proof that it's generated at compile time. – xiaofeng.li Feb 11 '18 at 23:17