简单的代码来获取java.lang.reflect.Type [英] Simple code to get java.lang.reflect.Type

查看:753
本文介绍了简单的代码来获取java.lang.reflect.Type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GSON 的toJson函数接受一个类型参数,它检查反射对象时键入。这对于将对象反射到集合中很有用。

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.

然而,我发现获得Type的唯一方法是通过一组丑陋的编码扭曲:

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) {
        ...
    }
}

有没有一种方法可以在不引用内部类变量的情况下初始化Type?伪代码看起来像这样:

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


推荐答案

toJson 看起来回答您的问题

The Javadoc for toJson looks to answer your question


typeOfSrc - src的特定通用类型。您可以使用TypeToken类获取此类型。例如,要获取Collection的类型,您应该使用:

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

所以在您的实例中。

private static final Type MY_OBJECT_TYPE = new TypeToken<List<MyObject>>(){}.getType();

这篇关于简单的代码来获取java.lang.reflect.Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆