简体   繁体   中英

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.

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.

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.

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.

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.

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

I don't know where you read that. The javadoc certainly doesn't say that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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