Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast object to ArrayList<String>

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);

    }
like image 504
padre Avatar asked Oct 09 '13 10:10

padre


2 Answers

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.

like image 126
Guillaume Avatar answered Sep 28 '22 18:09

Guillaume


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.

like image 22
Thilo Avatar answered Sep 28 '22 20:09

Thilo