Is there a way to instantiate a class defined in an anonymous inner class?

I accidentally wrote code and ran into a problem: how to create an instance of class E (shown below), which is defined inside an anonymous inner class; eg:

A c = new A() { class E{ //Statements } }; 
+3
java anonymous-inner-class
Mar 23 '17 at 18:34
source share
1 answer

You cannot write a program that uses the usual new call to do this: in order to instantiate a class, it must have a name . Anonymous inner classes, as follows from this term, have no name.

Thus, the class that exists inside this anonymous inner class also does not have a name; therefore, it cannot be created outside of this 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); } } 

Fingerprints:

 B inner foo inner C 

So, yes, given the fact that at runtime we can use the class name Test$1$C , and this reflection allows us to also create objects at runtime (see here for more information), the final answer: yes, this perhaps.

But just for the record: this does not mean at all that in the real code you need to do something like that. This is a nice little puzzle for learning creativity; but not suitable for anything in the real world.

In the real world, an inner class inside an anonymous inner class is a design error. The end of the story.

+2
Mar 23 '17 at 18:47
source share



All Articles