gpt4 book ai didi

java - 获取 java.lang.reflect.Type 的简单代码

转载 作者:搜寻专家 更新时间:2023-11-01 02:43:53 29 4
gpt4 key购买 nike

GSON的 toJson 函数接受一个类型参数来检查 Type反射物体时。这对于将对象反射(reflect)到集合中很有用。

但是,我能找到的唯一方法是通过一组丑陋的编码扭曲:

//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?伪代码看起来像这样:

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

最佳答案

toJson 的 Javadoc看起来可以回答你的问题

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 - 获取 java.lang.reflect.Type 的简单代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049170/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com