简体   繁体   中英

How to determine the Type of an object at runtime in Java for gson

Take a look at the following code, which works fine:

        MyData myData = new MyData(1, "one");
    MyData myData2 = new MyData(2, "two");
    MyData [] data = {myData, myData2};

    String toJson = gson.toJson(data, MyData[].class);

    MyData [] newData = gson.fromJson(toJson, MyData[].class);

MyData is just a simple class with int and String fields. This works perfectly fine. But what if the class is not known until runtime? eg It might not be "MyData", but could be a completely different class. The only thing we know is the name of the class (represented as a string), which was previously determined by the sender using Class.forName.

It works fine if the object is not an array, like so:

    final Class<?> componentType = Class.forName(componentClassName);
context.deserialize(someElement, componentType);

The above technique doesn't work for arrays though.

Any suggestions?

In java you can get the class of an object by calling

object.getClass();

From java docs:

class Test {
    public static void main(String[] args) {
        int[] ia = new int[3];
        System.out.println(ia.getClass());
        System.out.println(ia.getClass().getSuperclass());
    }
}

which prints:

class [I
class java.lang.Object

Do you mean that MyData would become a generic type T? If so you won't be able to do this due to Javas type erasure. The type T is only available at compile time.

You could create a method like:

public T decodeJSON(String json, Class<T> type) {
    GSON gson = new GSON();
    return gson.fromJson(json, type);
}
String toJson = gson.toJson(Class.forName(obj, runtimeClassName + "[]"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM