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

4
  • If constructor is public why you want to use reflection? Commented Jul 5, 2020 at 13:44
  • 1
    As the generics information is more or less lost at runtime (type-erasure) it should be getConstructor(Object.class, Object.class) Commented Jul 5, 2020 at 13:47
  • @mslowiak I'm using this thing from Minecraft Project, where Class differs every time the version changes. I want to create a version independent project, so I need a method to call the class without directly calling. Commented Jul 5, 2020 at 13:48
  • 1
    @dpr I'll try with the Object.class thanks! Commented Jul 5, 2020 at 13:49

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.