Java 将对象转换为 ArrayList<String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19269278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:34:56  来源:igfitidea点击:

cast object to ArrayList<String>

javacastingarraylist

提问by padre

is it possible to cast an Objectto e.g. ArrayList<String>

是否可以将 an 转换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 objto ArrayList<String>

在这里我想投一个Object obj,以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);

    }

采纳答案by Guillaume

In Java generics are not reified, i.e. 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 ArrayListcontains Documentobjects, the compiler raises a warning.

由于该运行时强制转换不会检查您的ArrayListcontainsDocument对象,因此编译器会发出警告。

回答by Thilo

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 Listand then check each element if it is a Documentor not.

您可以做的是强制转换为List然后检查每个元素是否为 a Document