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.

Share:
51,539
padre
Author by

padre

Updated on April 23, 2020

Comments

  • padre
    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 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);
    
        }
    
  • padre
    padre over 10 years
    but 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
    padre over 10 years
    I see ... so any suggetions how to re-write the method? Should I make the method generic as well, will then work?
  • hansvb
    hansvb over 10 years
    Best 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
    padre over 10 years
    yes 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
    Guillaume over 10 years
    As 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.