user2912198
user2912198

Reputation:

find constructor which has a generic parameter

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??

Upvotes: 4

Views: 134

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

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

Upvotes: 6

Dom
Dom

Reputation: 1722

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

Upvotes: -1

Related Questions