BQffen
BQffen

Reputation: 63

Getting Gson TypeToken from class name as a String

I want to do something like this - deserialize a class with generic type using Gson. The following code works like a charm.

Type type = new TypeToken<ActionTask<UptimeAction>>() {}.getType();

ActionTask task = (ActionTask) gson.fromJson(json, type);

But what if the type is provided as a String? I imagine something like the following.

String className = "UptimeAction";

Type type = ... // get the type somehow

ActionTask task = (ActionTask) gson.fromJson(json, type);

Is this possible at all?

Upvotes: 2

Views: 1170

Answers (1)

shmosel
shmosel

Reputation: 50726

Based on the Guava docs, you can create a method like this:

static <T> Type mapActionTask(Class<T> innerType) {
    return new TypeToken<ActionTask<T>>() {}
            .where(new TypeParameter<T>() {}, innerType)
            .getType();
}

And call it like this:

String className = "com.foo.UptimeAction";
Type type = mapActionTask(Class.forName(className)); 

Upvotes: 0

Related Questions