jeudi 30 mai 2019

Find Class by static value in the class in Java/Kotlin

I have a JSON serialized object, that looks like this

{
  "someData" : ... // data, structure of which varies based on the type of the serialized object
  "typeID" : 42 // integer constant that uniquely identifies type of the serialized object
}

I also have a Java library that looks like this:

abstract class GeneralClass {
  public abstract int getTypeID();
}

class SomeDataClass1 extends GeneralClass {
  public SomeDataClass1(/*arguments depend on type*/) {/*init data fields with arguments*/}

  /*public data fields*/

  public static final int typeID = 42

  @Override
  public int getTypeID() {
    return typeID;
  }
}

Each typeID uniquely identifies one of many classes from the Java library in the manner from the example. To use the functions from the library I need to construct the instance of the class from the serialized data; for that I will use gson. In order for gson to deserialize JSON into an object I need to pass it an instance of the Class object that corresponds to the typeID. How can I get the Class object corresponding to the class if I have its typeID?





Aucun commentaire:

Enregistrer un commentaire