How can we describe T<S>
as return type for a method
<T,S> T<S> getResult(Class<T> tClass, Class<S> sClass)
You can't, basically. There's no way of describing "a generic type with one type parameter" and using it like this.
Jon's right in that you can't do this in the general case. But if we think of a more specific case, say returning a specific type of List
of a specific type of elements, we can do something like this:
<T, L extends List<T>> L getResult(Class<T> tClass, Class<L> lClass)
But then there's the problem of calling it. Classes are parameterized by raw types only. So if we wanted to call it like this:
ArrayList<String> result = getResult(String.class, ArrayList.class);
It wouldn't work, because ArrayList.class
has type Class<ArrayList>
, not Class<ArrayList<String>>
.
But then we could use the super type token pattern, which Guava makes really easy with its 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 is only going to be of use if L
represents a concrete class. It's also possible to create a TypeToken
using type parameters, which won't help you at runtime.
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