Andrew Maddison

Flowerchild.

Java Generic Type Class Arguments and Generic Methods Syntax

I always have trouble finding the syntax for writing a method that takes and returns a generic type, and even more frequently the syntax for passing generic types to a generic method (eg, passing a List<Something>). This is a common pattern when deserializing JSON from http responses back into objects. So for my own easy retieval in future, here it is.

First the simple case – a generic method (just wrapping a call to a Javax Response.readEntity)

1
2
3
4
5
6
7
public <T> T genericMethod(Class<T> type) {
    Response response = someMethodThatGetsDataAndReturnsTheResponseObject();
    return response.readEntity(type);
}

//calling code:
SomeType result = genericMethod(SomeType.class);

And here’s the syntax of a method that takes a GenericType object as argument (ie, which can take the class of a generic type as an argument), and for the calling that generic method.

1
2
3
4
5
6
7
8
9
10
import javax.ws.rs.core.GenericType;
...

public <T> T genericMethod(GenericType<T> type) {
    Response response = someMethodThatGetsDataAndReturnsTheResponseObject();
    return response.readEntity(type);
}

//calling code:
List<SomeType> results = genericMethod(new GenericType<List<MrdArticleCitationDto>>(){});

One of the trickier aspects of this whole game, is what to name the identifier of the type parameter. You cant call it “class” as that’s a reserved keyword and opinion seems to be divided between “clazz” and “klass”. In this example I’ve opted out and called it “type”.

Comments