PatrickKR
PatrickKR

Reputation: 43

JAVA: Not sure about getting constructor with generic types in reflection

public class A<T, U> implements S<T, U> {
    private final T first;
    private final U second;

    public A(T first, U second) {
        this.first = first;
        this.second = second;
    }
}

Is there anyway to call the public constructor from reflection?

What I'm trying to do is

classLoader.loadClass("A").getConstructor(<Something Here>).newInstance()

Is it possible for me to do this?

Upvotes: 0

Views: 56

Answers (2)

Sweeper
Sweeper

Reputation: 271355

Since type parameters are erased, instead of passing in the fictional T.class and U.class (which doesn't mean anything), you should just pass in two Object.class, because that is what T and U erase to:

A.class.getConstructor(Object.class, Object.class)

You should also pass some parameters to newInstance. For example, to create a A<Integer, String>, you could do:

A<Integer, String> a = 
    (A<Integer , String>)A.class.getConstructor(Object.class, Object.class)
    .newInstance(1, "Hello World");

Upvotes: 1

Joni
Joni

Reputation: 111239

The type parameters T and U are erased and become Object when the code is compiled. So use Object.class to indicate the constructor parameter types.

Constructor aConstructor = aClass.getConstructor(Object.class, Object.class);

Upvotes: 1

Related Questions