I was randomly writing a code & encountered a problem: how to instantiate class E (shown below) which is defined within an anonymous inner class; like:
A c = new A() {
class E{ //Statements
}
};
I was randomly writing a code & encountered a problem: how to instantiate class E (shown below) which is defined within an anonymous inner class; like:
A c = new A() {
class E{ //Statements
}
};
You can't write a program that uses an ordinary call to new
to do that: in order for a class to be instantiated, it must have a name. Anonymous inner classes, as that term implies, do not have a name.
Thus a class that exists within that anonymous inner class also has no name; thus it can not be instantiated outside of that anonymous inner class.
But you can use reflection. See my Test.java:
import java.util.*;
import java.lang.reflect.*;
class B {
B() { System.out.println("B"); }
void foo() { System.out.println("B.foo"); }
}
public class Test{
B b;
void bar() {
b = new B() {
class C { C() { System.out.println("inner C"); } }
void foo() { System.out.println("inner foo"); }
};
b.foo();
}
public static void main(String[] args) throws Exception {
Test test = new Test();
test.bar();
Class<?> enclosingClass = Class.forName("Test$1");
Class<?> innerClass = Class.forName("Test$1$C");
Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);
Object innerInstance = ctor.newInstance(test.b);
}
}
This prints:
B
inner foo
inner C
So, yes, given the fact that we can use the mangled class name Test$1$C
at runtime, and that reflection allows us to instantiate objects at runtime, too (see here for details), the final answer is: yes, it is
possible.
But just for the record: that doesn't mean at all that one should ever do something like this in real code. This is a nice little puzzle to train creativity; but not suited for anything in the real world.
In the real world, an inner class within an anonymous inner class is a design bug. End of story.
© 2022 - 2024 — McMap. All rights reserved.