siiva33
siiva33

Reputation: 123

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

Upvotes: 2

Views: 1553

Answers (3)

Miquel
Miquel

Reputation: 4839

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

Upvotes: 1

christophmccann
christophmccann

Reputation: 4211

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

Upvotes: 1

Kevin
Kevin

Reputation: 25269

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

Upvotes: -1

Related Questions