Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Generic method by reflection in java

How to call a Custom Generic method by reflection in java?

class Person {   public <T> void print(T t)    {       System.out.println(t.toString());    } } 
like image 304
Hussein Zawawi Avatar asked May 24 '12 14:05

Hussein Zawawi


People also ask

How do you call a generic using reflection?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod: MethodInfo method = typeof(Sample). GetMethod(nameof(Sample. GenericMethod)); MethodInfo generic = method.

How do you call a generic method as a normal method?

Which of the following allows us to call generic methods as a normal method? Explanation: Type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets.

How do you write a reflection in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");


1 Answers

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 .class file.

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 of Object.

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 javap on 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 a List object.

like image 188
Edwin Buck Avatar answered Sep 22 '22 21:09

Edwin Buck