如何在运行时在Java中设置ArrayList的泛型类型? [英] How to set the generic type of an ArrayList at runtime in java?
问题描述
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: 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 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屋!Class c = Class.forName(string);
ArrayList<c> list = new ArrayList<c>();
Object
like we did in the old days when dinosaurs roamed the JVM, and gives you some compile-time type checking.