0

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 ??

LKC
  • 131
  • 9
  • 1
    Possible duplicate of [Get generic type of class at runtime](https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime) – Kartik May 29 '19 at 07:13
  • What library are you using? Jackson? – Lino May 29 '19 at 07:14
  • @Lino yes. I used Jacksion – LKC May 29 '19 at 07:17
  • That's interesting. I could solve the problem in a hacky way that I wouldn't share with someone who wouldn't understand it, but I couldn't find anything where jackson helps with that. – kumesana May 29 '19 at 08:58

1 Answers1

1

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.

Lino
  • 19,604
  • 6
  • 47
  • 65