如何在运行时在Java中设置ArrayList的泛型类型? [英] How to set the generic type of an ArrayList at runtime in java?

查看:420
本文介绍了如何在运行时在Java中设置ArrayList的泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我建立了自己的XML序列化(我知道还有其他人,甚至有一些内置到Java,但我自己学习,因为它非常好用)。我有序列化。我目前正在进行反序列化(读取XML文件并根据文件中的数据组装对象),并且遇到了设置泛型类型的问题。经过大量研究后,我想出了如何获得类的泛型,以便在序列化时可以编写它们,但我不知道如何做到这一点:

  Class c = Class.forName(string); 
ArrayList< c> list = new ArrayList< c>();

我在C#中看到了一些这样的答案,但显然C#比Java更通用,并且我无法在Java中复制那里的解决方案。这甚至可以完成,即使有反射?

解决方案

您不能。



Java中的泛型只是编译时语法糖。它使得它不必像往常一样在恐龙漫游JVM的过程中从 Object 扔掉所有东西,并给你一些编译时类型检查。



编辑以添加:在运行时保存了一些元数据,您可以通过反射将元数据保存到检查一个泛型类,但没有像你想要的。

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<c> list = new ArrayList<c>();

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.

这篇关于如何在运行时在Java中设置ArrayList的泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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