How to set common type of ArrayList at runtime in java?

Ok, so I am setting up my own XML serialization (I know that there are others, even some built-in in Java, but I do it myself to learn and because it is so cool to work). I have serialization down. I am currently involved in deserialization (reading in an XML file and assembling objects based on the data in the file), and I'm having trouble setting up generic types. After extensive research, I figured out how to get common class types so that I can write them when serializing, but I don't know how to do this:

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

I saw several answers for this in C #, but obviously C # is a bit more versatile than Java, and I cannot replicate the solutions there in Java. Can this even be done with reflection?

+6
source share
4 answers

You can not.

Generators in Java are just syntactic sugar with compilation. This makes it so that you don’t need to throw everything in and out of Object , as it was in the old days when dinosaurs roamed the JVM and gave you some kind of compilation type check.

Edit to add: At run time, there is some metadata that you can get through reflection to check for a common class, but nothing like what you want.

+11
source

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

See the articles below to understand erasing styles:

fooobar.com/questions/15712 / ...

Type Erasure Tutorial

0
source

else, what can you do (if you have a limited number of classes) .. you are checking the object using the "instance of" operator and depending on the location in your arraylist

 if(obj instance of abc) ArrayList<abc> al = new ArrayList<abc>(); 

you can nest if else or switch

0
source

No, Generics is only at compile time, only to check the type of compilation, so that you avoid casts that can be checked safely at compile time.

Think about it. If you could do what you want, it would be completely useless. For example, when using ArrayList<String> means that when you get an element from it, the compiler can infer at compile time that it is of type String , and therefore it allows you to assign it to type String in code without translation. In addition, if you try to add an element to it, the compiler can check at compile time that it is of type String , or it does not allow you to do this.

But you need a type parameter that is unknown at compile time. Thus, when you get an element from it, the compiler knows nothing about its type, so you can only assign it to an Object type. And when you try to insert something, the compiler does not know what type it should allow, so should it allow all types? Then there are no generics.

Thus, you should simply use the upper bound type as the type parameter. Like ArrayList<Object> list = new ArrayList<Object>();

0
source

All Articles