How to access a class which have the same name as the Method Local Inner class of a different class

Nikunj Gupta :

Consider the following code

class A{}
class B{
    void main(){
        A a1=new A();
        class A{}
        A a2=new A();
        System.out.println(a1); // A@___
        System.out.println(a2); // B$1A@____
    }
}

The class A and class B are not inside any package, How can I create the object of the outer class A inside main() after the method local inner class is created. In other words, how can I create the "a2" object, an object of outer class A?

I checked this by putting these classes in a Package, and I was able to create the object of outer class A using the fully qualified name. But, could not find a way to do the same when they are not inside any package.

Lino :

You can use Class.forName() to load the class you would like to instantiate:

class A {}

class B {
     public static void main(String[] args) throws Exception {
         A a1 = new A();
         class A {}
         A a2 = new A();
         Class<?> clazz = Class.forName("A");
         Object a3 = clazz.getDeclaredConstructor().newInstance();

         System.out.println(a1); // A@___
         System.out.println(a2); // B$1A@____  
         System.out.println(a3); // A@___
     }
}

This works, as the local class A in B.main() has a different fully qualified domain name as the one declared on the same level as B:

System.out.println(a1.getClass()); // class A
System.out.println(a2.getClass()); // class B$1A
System.out.println(a3.getClass()); // class A

I've had to use Object as the type of a3 because there is no way to reference the outer A inside main() once the local class A has been declared.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114716&siteId=1