开发者

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

开发者 https://www.devze.com 2023-02-13 18:03 出处:网络
Take a look at the following code, which works fine: MyData myData = new MyData(1, \"one\"); MyData myData2 = new MyData(2, \"two\");

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? e.g. 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 determi开发者_开发技巧ned 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?


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);
}


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


String toJson = gson.toJson(Class.forName(obj, runtimeClassName + "[]"));
0

精彩评论

暂无评论...
验证码 换一张
取 消