我正在学习 Java 中的一些反射功能,并且在使用此类测试 getConstructor()
函数时遇到了一个奇怪的问题。
public class IntegerSequence {
private Integer[] elements;
private int size;
private int MAX_SIZE = 100;
public IntegerSequence() {
elements = new Integer[MAX_SIZE];
size = 0;
System.out.println("Hello Guys");
}
}
该函数返回一个有效的构造函数,但永远不会打印“Hello Guys”消息。
此外,如果我删除 IntegerSequence
的构造函数,它也会返回一个有效的构造函数,并且不会抛出任何异常,即使 IntegerSequence
中不再有构造函数类(class)。
我读到 getConstructor()
只返回类中编码的构造函数,而不是由 Java 自动生成的构造函数,所以我有点迷失。
这是使用该函数的代码及其输出:
public void invokeDefaultConstructor(Class c){
Constructor build = null;
try {
build = c.getConstructor();
} catch (NoSuchMethodException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println(build.toString());
System.out.println(build.getName());
}
控制台输出:
public generics.IntegerSequence()
generics.IntegerSequence
您知道什么会导致这种行为吗?
最佳答案
The function return a valid constructor but the "Hello Guys" message is never printed.
这是预料之中的,因为你从来没有 call the constructor任何地方。您只能从类中获取构造函数。
I read that getConstructor() only return a constructor coded in the class and not one made automatically by Java
我不知道你在哪里读到的。 The javadoc当然不会这么说。
关于java - getConstructor() 返回一个未实现的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59685462/