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.
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.