Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java local class .class file names

Tags:

java

What will be the name of the .class file when local classes with same name are present in more than one instance method of same class? How can JVM differentiate these local classes?

like image 308
Sheo Avatar asked Sep 28 '26 14:09

Sheo


2 Answers

Code:

public class Test {

    public static void main(String[] args) {
    }

    public void method1() {
        class class1 {

        }
    }

    public void method2() {
        class class1 {

        }
    }
}

Generated classes:

Test.class
Test$1class1.class
Test$2class1.class

So it's OuterClass$(number)InnerClass

like image 159
Tudor Avatar answered Sep 30 '26 03:09

Tudor


With both local classes and anonymous classes the compiler adds a number to the generated name.

Compiling the below code produced classes Test.class, Test$1Local.class, Test$2Local.class and Test$1Another.class so the compiler (jdk1.6.0_24) always adds a number to the name (maybe to avoid conflicts with inner classes) and if there are two local classes with the same name then it increments the number to avoid conflicts.

public class Test {
    public void foo() {
        class Local {
        }
    }

    public void bar() {
        class Local {
        }
    }

    public void baz() {
        class Another {
        }
    }
}
like image 30
Esko Luontola Avatar answered Sep 30 '26 03:09

Esko Luontola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!