Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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

<T,S> T<S> getResult(Class<T> tClass, Class<S> sClass)
like image 358
Andrei N Avatar asked Dec 12 '22 15:12

Andrei N


2 Answers

You can't, basically. There's no way of describing "a generic type with one type parameter" and using it like this.

like image 187
Jon Skeet Avatar answered Jan 12 '23 01:01

Jon Skeet


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.

like image 42
Mark Peters Avatar answered Jan 11 '23 23:01

Mark Peters