asteri
asteri

Reputation: 11592

How are anonymous inner classes identified in the system?

How is an anonymous inner class created and identified by the JVM?

For example, I can make several anonymous inner classes of the same interface, each with its own, unique implementations. And these can be all within the same (explicit) class, so the class which it is located in can't be the entire identifier. So what information does the JVM use to determine one anonymous object from another? (The only thing I could think of is the line number upon which it was declared, but that seems a bit too human to be the real answer.)

Is there a way to see the .class files that the compiler generates for these? Or are they created dynamically at run time?

Upvotes: 2

Views: 98

Answers (2)

Juvanis
Juvanis

Reputation: 25950

You can get some insight by trying a simple example like this:

public class A {
    public static void main(String[] args)
    {
        L a = new L() { };
        L b = new L() { };
    }
}

interface L { }

Running the code above produces 3 separate class files:

A.class
A$1.class
A$2.class

Upvotes: 3

PermGenError
PermGenError

Reputation: 46428

Java code:

   public static void main(String...args) {
    TestInter t = null; 
            t = new TestInter() { //com/next/b/Test$1 
            };
            t= new TestInter() {  //com/next/b/Test$2
            };
     }

ByteCode:

 L0
    LINENUMBER 8 L0
    ACONST_NULL
    ASTORE 1
   L1
    LINENUMBER 9 L1
    NEW com/nextcontrols/bureautest/Test$1
    DUP
    INVOKESPECIAL com/next/b/Test$1.<init>()V
    ASTORE 1
   L2
    LINENUMBER 11 L2
    NEW com/nextcontrols/bureautest/Test$2
    DUP
    INVOKESPECIAL com/next/b/Test$2.<init>()V
    ASTORE 1

Note the INVOKESPECIAL lines in the byte code

Upvotes: 3

Related Questions