Simple code to get java.lang.reflect.Type

2019-07-19 09:00发布

GSON's toJson function takes a type argument which checks the Type when reflecting the object. This is useful for reflecting objects into a collection.

However, the only way I can find to obtain the Type is through an ugly set of coding contortions:

//used for reflection only
@SuppressWarnings("unused")
private static final List<MyObject> EMPTY_MY_OBJECT = null;
private static final Type MY_OBJECT_TYPE;

static {
    try {
        MY_OBJECT_TYPE = MyClass.class.getDeclaredField("EMPTY_MY_OBJECT").getGenericType();
    } catch (Exception e) {
        ...
    }   
}

private List<MyObject> readFromDisk() {

    try {
        String string = FileUtils.readFileToString(new File(JSON_FILE_NAME), null);
        return new Gson().fromJson(string, MY_OBJECT_TYPE);
    } catch (Exception e) {
        ...
    }
}

Is there a way of initializing the Type without referencing internal class variables? The pseudocode would looks something like this:

private static final Type MY_OBJECT_TYPE = TypeUtils.generate(List.class, MyObject.class);

2条回答
啃猪蹄的小仙女
2楼-- · 2019-07-19 09:09

The Javadoc for toJson looks to answer your question

typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection, you should use:

Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();

So in your instance.

private static final Type MY_OBJECT_TYPE = new TypeToken<List<MyObject>>(){}.getType();
查看更多
姐就是有狂的资本
3楼-- · 2019-07-19 09:18

It is also possible to do like this:

 private static final Type MY_OBJECT_TYPE = TypeToken.getParameterized(List.class, MyObject.class).getType();
查看更多
登录 后发表回答