简体   繁体   English

将对象强制转换为ArrayList <String>

[英]cast object to ArrayList<String>

is it possible to cast an Object to eg ArrayList<String> 是否可以将Object为例如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> 我想将Object objArrayList<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, ie their generic type is not used when casting. 在Java中,泛型不具体化,即在转换时不使用它们的泛型类型。

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. 由于运行时强制转换不会检查ArrayList包含Document对象,因此编译器会发出警告。

No, that is not possible due to how generics are implemented in Java. 不,由于Java中如何实现泛型,这是不可能的。

The type information is not available at runtime, so it cannot be checked by instanceof . 类型信息在运行时不可用,因此无法通过instanceof进行检查。

What you can do is cast to List and then check each element if it is a Document or not. 您可以做的是转换为List ,然后检查每个元素是否为Document

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM