How can we describe T <S> as a return type for a method using generics in java

How can we describe T<S> as a return type for a method

 <T,S> T<S> getResult(Class<T> tClass, Class<S> sClass) 
+4
source share
2 answers

You cannot, in principle. There is no way to describe a “generic type with one type parameter” and use it as follows.

+9
source

John is right that you cannot do this in the general case. But if we think about a more specific case, say, by returning a specific List type of a certain type of element, we can do something like this:

 <T, L extends List<T>> L getResult(Class<T> tClass, Class<L> lClass) 

But then the problem arises of calling it. Classes are parameterized only by raw types. Therefore, if we wanted to call it this way:

 ArrayList<String> result = getResult(String.class, ArrayList.class); 

This will not work because ArrayList.class is of type Class<ArrayList> , not Class<ArrayList<String>> .

But then we could use the super-type token pattern, which Guava makes very easy with the TypeToken class:

 <T, L extends List<T>> L getResult(Class<T> tClass, TypeToken<L> lType) { // use lType.getRawType()... } ArrayList<String> result = getResult(String.class, new TypeToken<ArrayList<String>>(){}); 

Of course, this will only be useful if L represents a particular class. It is also possible to create a TypeToken using type parameters that will not help you at runtime.

+4
source

Source: https://habr.com/ru/post/1480530/


All Articles