繁体   English   中英

实例化类时引发异常

[英]Throws Exception while instantiating class

我有一个非常简单的问题-

我有一个名为DEClient的类,其构造函数如下:

public DEClient(List<DEKey> keys) {
    process(keys);
}

DEKey类是这样的-

public class DEKey {

    private String name;
    private String value;

    public DEKey(){
        name = null;
        value = null;
    }

    public DEKey(String name, String value){
        this.name  = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

现在,我试图实例化DEClient构造函数。 因此,我需要拥有List<DEKey>

所以我要做的是使用service.getKeys() (将返回String )和id作为值实例化DEKey类,如下所示。

DEKey dk = new DEKey(service.getKeys(), id);

//The below line throws exception whenever I am running.
DEClient deClient = new DEClient((List<DEKey>) dk);

我在这里做什么错?

您需要首先创建一个List ,然后将密钥添加到该List 由于DEKey 不是 List ,因此像您一样进行铸造不是实现的方法,并且对其进行铸造将抛出ClassCastException

DEKey dk = new DEKey(service.getKeys(), id);

List<DEKey> list = new ArrayList<DEKey>();
list.add (dk);

DEClient deClient = new DEClient(list);

暂无
暂无

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

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