4

how can I find the constructor of a class which get passed a generic parameter. For example such a class:

class myClass<T> {
    public myClass(T val1, Long val2 String val3){ 
        ...
    }
}

Using the usual reflection approach getConstructor() lacks the proper parameters:

Constructor<?> myConstructor = myClass.class.getConstructor( ??what here??, Long.class, String.class);

Any ideas??

LadyCailin
  • 849
  • 10
  • 26

2 Answers2

6

Object is the type: Object.class

Because of generic type erasure, there is no other more specific type available.

More good stuff here: get-type-of-a-generic-parameter-in-java-with-reflection

e.g., for

public class Bar<T> {
   private T t;

   public Bar(T t) {
      this.t = t;
   }

   @Override
   public String toString() {
      return t.toString();
   }
}

This will return "foo":

Class<?>[] paramArray = {Object.class};
Constructor<?> myConstructor = Bar.class.getConstructor(paramArray);
String foo = "foo";
Bar myBar = (Bar) myConstructor.newInstance(foo);
System.out.println(myBar);
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
-1

It's fairly straight forward.

Constructor<T> myConstructor = myClass.class.getConstructor( T val, Long.class, String.class);

If you want a string, it looks like this:

Constructor<String> myConstructor = myClass.class.getConstructor( String val, Long.class, String.class);

If you want a int, it looks like this:

Constructor<int> myConstructor = myClass.class.getConstructor( int val, Long.class, String.class);
Dom
  • 1,687
  • 6
  • 27
  • 37