LKC
LKC

Reputation: 141

I want Generic class's "Class<T>" with "Class variable"

I want to get Generic class's type variable for JsonDeserialize.

Class Data<T> {
  private T data;
}

Class DataType {
  private String dummy;
}


Class dataTypeClass = DataType.class;


// I want get this.
Class dataClass = Data<dataTypeClass>.class;


I've tried it like this way, It doesn't work.

Could I get Data.class ??

Upvotes: 0

Views: 57

Answers (1)

Lino
Lino

Reputation: 19926

If you're using Jackson as your library. You can just use TypeReference:

TypeReference<Data<DataType>> r = new TypeReference<Data<DataType>>() {};
...
Data<DataType> data = objectMapper.readValue(json, r);

This code will create a new anonymous sub class of TypeReference parameterized with <Data<DataType>>. This class internally uses a "hackaround" to get the generic parameter, which then is picked up by Jackson to deserialize your JSON.

Upvotes: 1

Related Questions