简体   繁体   English

getConstructor() 返回未实现的构造函数

[英]getConstructor() return a constructor that is not implemented

I'm learning some of the reflection features in Java and I got a strange problem testing the getConstructor() function with this Class.我正在学习 Java 中的一些反射功能,并且在使用getConstructor()测试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");
  }
}

The function returns a valid constructor but the "Hello Guys" message is never printed.该函数返回一个有效的构造函数,但永远不会打印“Hello Guys”消息。

Furthermore, If I delete the constructor of IntegerSequence , it also return a valid constructor and doesn't throw any exception, even if there is no one anymore in IntegerSequence class.此外,如果我删除IntegerSequence的构造函数,它也会返回一个有效的构造函数并且不会抛出任何异常,即使IntegerSequence类中不再有异常。

I read that getConstructor() only returns a constructor coded in the class and not one made automatically by Java so I'm a bit lost.我读到getConstructor()只返回类中编码的构造函数,而不是由 Java 自动生成的构造函数,所以我有点迷茫。

Here is the code that use the function and it's output:这是使用该函数的代码及其输出:

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());
  }

console Output:控制台输出:

public generics.IntegerSequence()
generics.IntegerSequence

Do you know what could cause that kind of behaviour ?你知道什么会导致这种行为吗?

The function return a valid constructor but the "Hello Guys" message is never printed.该函数返回一个有效的构造函数,但永远不会打印“Hello Guys”消息。

That's expected, since you never call the constructor anywhere.这是意料之中的,因为您永远不会任何地方调用构造函数 You only get the constructor from the class.您只能从类中获取构造函数。

I read that getConstructor() only return a constructor coded in the class and not one made automatically by Java我读到 getConstructor() 只返回类中编码的构造函数,而不是由 Java 自动生成的构造函数

I don't know where you read that.我不知道你在哪里读到的。 The javadoc certainly doesn't say that. javadoc当然没有这么说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM