java - getConstructor() 返回一个未实现的构造函数

标签 java reflection constructor

我正在学习 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/

相关文章:

java - 如何反转字节数组中的 UTF-8 编码?

java - 如何使用字符串引用类中的公共(public) int

java - 来自类变量的 JNI jstring?

Java 为抽象类声明类吗?

c# - 从抽象类引用继承的 EntitySet 的 dapper PropInfo Setter 为 null

c#-4.0 - 使用具有无参数构造函数约束的泛型类型的接口(interface)?

带大括号 {} 的 Javascript 构造函数

java - 如何正确地将 simpleStringProperty 中的字符串值显示到 listView 上

c++ - 原始构造函数与转换转换

java - 使用反射从父类(super class)中的子类中查找方法