动机: 我的一个朋友在大学为新生提供辅导,今天我拜访了他。他为全班做了练习,我做到了,这是最复杂,最糟糕的方式。但是,当我尝试实例化一个嵌套类时,我偶然发现了一个意外的反射异常。
我打破了这些课程以获得一个更简单的例子(忽略这个事实,没有人会这样做):
public class DeepJavaNested {
/**
* A method, that holds an inner class
*/
public void outerClassFoo() {
/**
* Class enclosed by method
*/
class InnerClass {
/**
* Default constructor of InnerClass
*/
public InnerClass() {
System.out.println("Constructed instance of " + getClass().getName());
}
/**
* Just to test the created object
*/
public void foo() {
System.out.println("Successfully invoked a pointless method!");
}
}
}
}
另外,我有一个主要的方法,尝试两件事。首先,它获取嵌套类的Reflection类对象:
Class<?> innerClass = null;
try {
innerClass = Class.forName("deep.nested.DeepJavaNested$1InnerClass");
} catch (ClassNotFoundException e) {
assert false;
}
然后,它尝试通过两种方式调用构造函数,Reflection提供:
try {
// get the (obviously declared) default constructor for the inner class
Constructor<?> innerClassConstructor = innerClass.getConstructor();
// set it accessible, just in case, I am missing something, that would hide it
innerClassConstructor.setAccessible(true);
// invoke the constructor and get an instance of InnerClass
Object instanceOfInnerClass = innerClassConstructor.newInstance();
// invoke test method
innerClass.getMethod("foo").invoke(instanceOfInnerClass);
} catch (NoSuchMethodException e) {
System.err.println("Reflection failed to find constructor: " + e.getMessage());
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
而且,因为我知道,这不起作用;第二种方式:
try {
// invoke the default constructor using the evil way
Object innerClassObj = innerClass.newInstance();
// invoke test method
innerClass.getMethod("foo").invoke(innerClassObj);
} catch (InstantiationException e) {
System.err.println("Reflection failed to instance class: " + e.getMessage());
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
应用程序的结果输出:
Reflection failed to find constructor: deep.nested.DeepJavaNested$1InnerClass.<init>()
Reflection failed to instance class: deep.nested.DeepJavaNested$1InnerClass
很明显,Java找不到 public 构造函数,也无法用凌乱的方式创建类的实例,也期望默认构造函数可用。
我现在的问题:我是否遗漏了某些内容,或者Java Reflection无法实现类,这些类没有被类封闭,而是通过方法?
整个代码示例也可作为Gist: https://gist.github.com/Cydhra/f1c32e8314ee44809f7874d5a19a8842