Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get type arguments class of generic method parameter? [duplicate]

Tags:

java

generics

How to get the type argument of an argument passed to a method ? For example I have

List<Person> list = new ArrayList<Person>(); 

public class Datastore {

  public <T> void insert(List<T> tList) {
     // when I pass the previous list to this method I want to get Person.class ; 
  }
} 
like image 791
Adelin Avatar asked Feb 19 '13 08:02

Adelin


People also ask

How do you find the class of a generic type?

You can get around the superfluous reference by providing a generic static factory method. Something like public static <T> GenericClass<T> of(Class<T> type) {...} and then call it as such: GenericClass<String> var = GenericClass. of(String. class) .

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

How many type parameters can be used in a generic class?

You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.


1 Answers

Due to type erasure, the only way you can do it is if you pass the type as an argument to the method.

If you have access to the Datastore code and can modify you can try to do this:

public class Datastore {
    public T void insert(List<T> tList, Class<T> objectClass) {
    }
}

and then call it by doing

List<Person> pList = new ArrayList<Person>();
...
dataStore.insert(pList, Person.class);

Every response I've seen to this type of question was to send the class as a parameter to the method.

like image 186
Denis Rosca Avatar answered Nov 09 '22 16:11

Denis Rosca