How to call a Custom Generic method by reflection in java?
class Person
{
public <T> void print(T t)
{
System.out.println(t.toString());
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Generics are erased at compile time, they only provide extra information to the compiler to determine errors. They do not actually change the signature of the method in the
.classfile.This means that you call a generic method by reflection in Java exactly the same way as you would call a non-generic method in Java, except that instead of specifying a type of
T, you would specify a type ofObject.There are so many tutorials on how to call a regular method by reflection that I hesitate to add yet another; however, if you really need direction on how to call a method by reflection, please add a comment below and I’ll add the necessary code.
If you find that things are not working as expected, you can always run
javapon the compiled class file to verify that you are using the right objects in the argument list. It might be possible that if you specify a<T extends List>type generic signature, the resulting parameter object might actually be aListobject.