在 Java 中,有没有办法或技巧来反射地实例化本地类?
这是我的测试课:
package com.example.localclass;
import org.junit.Test;
public class LocalClassInstantiationTest {
@Test
public void testInstantiateLocalClassReflectively() {
System.out.println("About to define local class");
class LocalClass {
void print() {
System.out.println("Hello world");
}
}
System.out.println("--------------------Direct instantiation------------------------");
LocalClass localClassInstance;
localClassInstance = new LocalClass();
localClassInstance.print();
System.out.println("--------------------Reflective instantiation--------------------");
Class<LocalClass> localClazz = LocalClass.class;
System.out.println("Local class name: " + localClazz.getName() );
System.out.println("Local class canonical name: " + localClazz.getCanonicalName() );
System.out.println("Local class constructors array length: " + localClazz.getConstructors().length);
System.out.println("About to create local class instance reflectively");
try {
localClassInstance = localClazz.newInstance();
localClassInstance.print();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
当我运行它时,我得到以下结果:
About to define local class
--------------------Direct instantiation------------------------
Hello world
--------------------Reflective instantiation--------------------
Local class name: com.example.localclass.LocalClassInstantiationTest$1LocalClass
Local class canonical name: null
Local class constructors array length: 0
About to create local class instance reflectively
java.lang.InstantiationException: com.example.localclass.LocalClassInstantiationTest$1LocalClass
at java.lang.Class.newInstance0(Class.java:357)
at java.lang.Class.newInstance(Class.java:325)
at com.example.localclass.LocalClassInstantiationTest.testInstantiateLocalClassReflectively(LocalClassInstantiationTest.java:32)