在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)
在您的例子中,问题是您的类没有空构造函数。newInstance()假定您有一个,如果没有则失败。
如果你在一个静态方法中运行这个,比如main,你不会得到这个错误。
这是因为您有一个非静态匿名类,并且无论您是否使用它,都隐式地需要对外部类LocalClassInstantiationTest的引用。
你可以试试这个
System.out.println("Local class constructors array length: " +
localClazz.getDeclaredConstructors().length);
System.out.println("About to create local class instance reflectively");
try {
localClassInstance = localClazz
.getDeclaredConstructor(LocalClassInstantiationTest.class)
.newInstance(this);
localClassInstance.print();
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
和你的程序打印
About to define local class
--------------------Direct instantiation------------------------
Hello world
--------------------Reflective instantiation--------------------
Local class name: LocalClassInstantiationTest$1LocalClass
Local class canonical name: null
Local class constructors array length: 1
About to create local class instance reflectively
Hello world