vendredi 10 janvier 2020

getConstructor() return a constructor that is not implemented

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

I'm learning some of the reflection features in Java and I got a strange problem testing the getConstructor() function with the above Class.

The function return 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 return 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 ?





Aucun commentaire:

Enregistrer un commentaire