Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a class with type parameter as type parameter for generic method in Java

People also ask

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

How do you provide a generic parameterized type?

In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.

Can generics take multiple type parameters?

Multiple parametersYou 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.

Which type parameter is used for a generic class to return and accept any type of object?

Which of these type parameters is used for a generic class to return and accept any type of object? Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable. 3.


This is actually possible in Java, using some "tricks". Don't succumb to pressure from the C# fanatics! (j/k)

The "trick" is to create a class that extends a generic type, and access the value of the type parameter of the parent class through the Type returned by .getGenericSuperclass() or .getGenericInterfaces().

This is quite cumbersome. To simplify our lives, Google has already written most of the boring part of the code for us, and made it available through Guava.

Check the TypeToken class, which does exactly what you want. For example:

TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() {};

Then you pass around a TypeToken<T> instead of a Class<T> and that's all. It provides you with methods to do reflection on the type represented by T.

What this is doing internally is simply calling .getClass().getGenericSuperclass() (or ...Interfaces()), then some ugly casts from Type to ParameterizedType and retrieving all the information from there (.getActualTypeArguments(), etc).

Finally, if you want to do something similar with Dependency Injection (ie, suppose you need to inject a Class<T> on the constructor of a class, or you want to get an instance of some parameterized interface, in which the instance should depend on the type parameter), Google Guice (a DI container from Google) has a very similar mechanism to solve the problem, called TypeLiteral. The use and the code behind the scenes are almost identical to TypeToken from Guava. Check it here: TypeLiteral