最近遇到一个问题,java非静态的内部类,在调用到java.lang.Class.getConstructor(Class<?>...)这个方法时,抛出了异常NoSuchMethodException,这是为什么呢?
仔细看java.lang.Class.getConstructor(Class<?>...)这个方法的注释,如下:
/**
* Returns a <code>Constructor</code> object that reflects the specified
* public constructor of the class represented by this <code>Class</code>
* object. The <code>parameterTypes</code> parameter is an array of
* <code>Class</code> objects that identify the constructor's formal
* parameter types, in declared order.
*
* If this <code>Class</code> object represents an inner class
* declared in a non-static context, the formal parameter types
* include t

在尝试使用java.lang.Class.getConstructor方法获取非静态内部类的构造器时,遇到了NoSuchMethodException。注释表明,对于非静态内部类,需要提供外部类类型作为参数,而非内部类本身。通过示例代码展示正确调用方式,即传入外部类类型,否则会抛出异常。要完全理解这一行为的实现原理,需要进一步阅读源代码。
最低0.47元/天 解锁文章
173万+

被折叠的 条评论
为什么被折叠?



