8

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

    }
4
  • 2
    What is the problem? What is the error you're getting? Commented Oct 9, 2013 at 10:22
  • you say that, want to cast an Object obj to ArrayList<String> but in the last line u seem to cast to ArrayList<Document> Commented Oct 9, 2013 at 10:22
  • I wrote e.g. ArrayList<String>, but you are right, the type should be Document Commented Oct 9, 2013 at 10:24
  • Note that there will be a lot of "else if" and not else{ if(){}else{} } like it would be if you wrote this in python or something that cared about indentation and lines. I don't think the actual outcome will differ though. Commented Oct 9, 2013 at 10:37

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see ... so any suggetions how to re-write the method? Should I make the method generic as well, will then work?
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.
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.

3 Comments

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>
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.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.