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 ;
}
}
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) .
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.
A Generic class can have muliple type parameters.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With