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
to ArrayList<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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With