Creating parameterized type object using anonymous class

Sure you could, and for most applications it would probably be sufficient.

However, using the first method, you get a more refined object. Let's say for instance that you create an object type1 using the first method, and type2 using the second method. Then type1.equals(type2) would return true (since the first method returns an object that properly implements the equals-method) but type2.equals(type1) would return false (since in the second method, you haven't overridden the equals-method, and are using the implementation from Object).

Same reasoning applies to other (sometimes useful methods) such as toString, hashCode etc. The second method does not provide useful implementations of these.


If you include Google's Guava library in your project (you should; it's great), use its TypeToken to get a type. Google's Gson library (for interacting with JSON) has a similar version. Both are used like this (to get a Type representing List<String>:

Type t = new TypeToken<List<String>>(){}.getType();

If you don't want to rely on any third-party libraries, you can still use anonymous types to get a generic concrete type with one line of code (this technique will not work with interfaces and could be more trouble than it's worth for Abstract Types). To get a Type representing HashMap<String, String>, do this:

Type t = new HashMap<String, String>(){}.getClass().getGenericSuperclass();

I have verified that resulting Type instance .equals() the Type instances created by Gson's TypeToken, though have not verified the same for Guava's version of TypeToken, which I do not have access to at the moment. (Guava is a more general-purpose library that is so handy for all sorts of things, you should probably be using it anyways.)


In addition to the mentioned libs from Google there is also a lib from Apache that does the job.

import org.apache.commons.lang3.reflect.TypeUtils;
...
ParameterizedType type = TypeUtils.parameterize(List.class, Double.class);
...

Finde code on GitHub here and Maven artifacts here.

Tags:

Java

Generics