java reflect type,简单的代码来获取java.lang.reflect.Type

该博客讨论了如何在Java中使用Gson库将JSON字符串反序列化为特定的泛型类型。作者指出,通常需要通过反射获取类型信息,但这种方法涉及内部类变量。他们分享了一种通过TypeToken获取类型的方法,避免了对内部类的依赖,提高了代码的可读性和维护性。
摘要由CSDN通过智能技术生成

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

解决方案

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

So in your instance.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值