为什么子类的默认构造函数不能通过反射获得?
Why is the default constructor of a Subclass not available through reflection?
当运行这个:
import java.util.Arrays;
public class TestA {
public static void main(String[] args) {
System.out.println(Arrays.toString(TestB.class.getConstructors()));
}
}
class TestB extends TestA {
}
结果会是
[]
使用反射调用默认构造函数时,代码会崩溃NoMethodFoundException: TestB.<init>()
。所以 JVM 不知何故不知道有一个默认构造函数。但是当你简单地调用 new TestB()
时,一切都很好(应该是这样)。
除此之外,当我反编译 .class 文件时,两个 class 都有一个默认构造函数。
引擎盖下发生了什么或者我错过了什么?
Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
TestB
的构造函数不是public!根据 JLS §8.8.9:
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
- The default constructor has the same accessibility as the class.
- ...
TestB
具有“包”访问级别(无访问修饰符),因此默认构造函数也具有该访问级别。因此,getConstructors
不将其包含在其返回的数组中。事实证明,这与 TestB
是 TestA
.
的子类无关
如果你想得到它,使用getDeclaredConstructors
。
当运行这个:
import java.util.Arrays;
public class TestA {
public static void main(String[] args) {
System.out.println(Arrays.toString(TestB.class.getConstructors()));
}
}
class TestB extends TestA {
}
结果会是
[]
使用反射调用默认构造函数时,代码会崩溃NoMethodFoundException: TestB.<init>()
。所以 JVM 不知何故不知道有一个默认构造函数。但是当你简单地调用 new TestB()
时,一切都很好(应该是这样)。
除此之外,当我反编译 .class 文件时,两个 class 都有一个默认构造函数。
引擎盖下发生了什么或者我错过了什么?
Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
TestB
的构造函数不是public!根据 JLS §8.8.9:
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
- The default constructor has the same accessibility as the class.
- ...
TestB
具有“包”访问级别(无访问修饰符),因此默认构造函数也具有该访问级别。因此,getConstructors
不将其包含在其返回的数组中。事实证明,这与 TestB
是 TestA
.
如果你想得到它,使用getDeclaredConstructors
。