Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the generic type of an ArrayList at runtime in java?

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?

like image 415
jchitel Avatar asked Feb 03 '13 08:02

jchitel


People also ask

What is the generic type of ArrayList?

The ArrayList class is similar to the C++ vector template. Both ArrayList and vector are generic types.

Is generic type information present at runtime?

Is generic type information present at runtime? Generic type information is not present at runtime. C. You cannot create an instance using a generic class type parameter.

How do I set generics in Java?

Syntax of a Generic SetSet< T > set = new HashSet< T >(); Above syntax is a generalized way to use T to show the generic behavior of a Set which means that T can be replaced with any non-primitive like Integer, String, Double, Character, or any user-defined type.


1 Answers

You cannot set generic type at runtime. All generic type information is erased at compile time.

See below articles to understand type erasure:

Type Erasure StackOverflow

Type Erasure Tutorial

like image 193
Amit Avatar answered Sep 22 '22 06:09

Amit