cast object to ArrayList<String>
51,539
Solution 1
In Java generics are not reified, i.e. their generic type is not used when casting.
So this code
setDocs((ArrayList<Document>)obj);
will be executed as
setDocs((ArrayList)obj);
As that runtime cast won't check your ArrayList
contains Document
objects, the compiler raises a warning.
Solution 2
No, that is not possible due to how generics are implemented in Java.
The type information is not available at runtime, so it cannot be checked by instanceof
.
What you can do is cast to List
and then check each element if it is a Document
or not.
Author by
padre
Updated on April 23, 2020Comments
-
padre about 4 years
is it possible to cast an
Object
to e.g.ArrayList<String>
the code below gives an example of the problem. The Problem is in the last row
setDocs((ArrayList<Document>)obj);
where I want to cast an
Object obj
toArrayList<String>
public void setValue(Object obj) { if(obj instanceof TFile) setTFile((TFile)obj); else if(obj instanceof File) setFile((File)obj)); else if(obj instanceof Document) setDoc((Document)obj); else if(obj instanceof ArrayList) setDocs((ArrayList<Document>)obj); }
-
padre over 10 yearsbut I know, if its from type ArrayList, then it will be ArrayList<Document>. The compiler is giving me warning on the next row, where I cast to ArrayList<Document>
-
padre over 10 yearsI see ... so any suggetions how to re-write the method? Should I make the method generic as well, will then work?
-
hansvb over 10 yearsBest you can do is suppress the warning. And re-think if you really need this instanceof monster. In most programs, types should be known at compile time, without the need for this dynamic inspection.
-
padre over 10 yearsyes I know, but the code is very old and compiles with Java 1.4, so I am trying to update it to Java 1.7 and wanted to clean up some basic warning like this. Thanks any way
-
Guillaume over 10 yearsAs long as you have to cast you will have the issue. You can either ignore the compiler warning or directly call setDocs(ArrayList<Document>) when you have the correct type.