holmis83
holmis83

Reputation: 16604

Check if Type instance equals generic type

I need to implement a Java interface that has a method similar to this:

boolean canWrite(Type t);

In my case it should return true if the type is List<URI>.

I though of doing something like return t.equals(URI_LIST_TYPE), but I don't know how to get an instance of Type that represents List<URI>.

Is there a pretty way to do it?

Upvotes: 1

Views: 601

Answers (2)

holmis83
holmis83

Reputation: 16604

Since I already use Spring I found ParameterizedTypeReference class to be useful. (I guess it is similar to Guava's TypeToken.) In my case:

URI_LIST_TYPE = (new ParameterizedTypeReference<List<URI>>() {}).getType();

There is also the possibility to compare as string:

t.toString().equals("java.util.List<java.net.URI>")

Or the more defined behaviour with Java 8:

t.getTypeName().equals("java.util.List<java.net.URI>")

Upvotes: 0

Raffaele
Raffaele

Reputation: 20885

You need a type token, for example the one in Guava that is used like this

new TypeToken<List<String>>() {}

This works because (anonymous) subclasses retain the information about the type parameters at runtime, and are then inspectable by reflection libraries.

As a side node, when designing an API that deals with reflection, don't use Class<E> as an input parameter if parameterized types can come into play

Upvotes: 2

Related Questions