java arraylist 泛型,如何在运行时在Java中设置ArrayList的泛型类型?

Ok, so I am setting up my own XML serialization (I know there are others out there, even some built in to Java, but I am doing it myself to learn and because it is so awesome to work with). I have serialization down. I am currently on the deserialization (reading in the XML file and assembling objects based on the data in the file) and I am running into problems with setting generic types. After extensive research, I figured out how to get the generic types of a class so I could write them when serializing, but I have no clue how to do this:

Class c = Class.forName(string);

ArrayList list = new ArrayList();

I have seen a few answers for this in C#, but obviously C# is a bit more versatile than Java, and there is no way that I can replicate the solutions there in Java. Can this even be done, even with reflection?

解决方案

You can't.

Generics in Java are simply compile-time syntactic sugar. It makes it so you don't have to cast everything to and from Object like we did in the old days when dinosaurs roamed the JVM, and gives you some compile-time type checking.

Edit to add: There is some metadata preserved at runtime that you can get at via reflection to inspect a generic class, but nothing like what you want.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值