我的代码在运行时失败并出现 ClassCastException
。我尝试过调试但没有成功。我已经声明了一个带有字段的类主题,并尝试将该类的对象加载到列表中。下面是代码。它在以下行失败:List items = (List)(it.next())
。为泛型添加 ?
没有帮助。我猜想该对象已被强制转换,尽管 List
声明中没有提到泛型。我在这里缺少一个基本概念吗?
在下面的方法中,我尝试将数据编码到 xml 文件中。
private void encodeSection(PrintStream output, Indenter indenter,
String name, List list) {
String indent = indenter.makeString();
output.println(indent + "<" + name + "s>");
indenter.in();
String indentNext = indenter.makeString();
if (list == null) {
// the match is any
output.println(indentNext + "<Any" + name + "/>");
} else {
String nextIndent = indenter.makeString();
Iterator it = list.iterator();
indenter.in();
while (it.hasNext()) {
List items = (List)(it.next());//-------------> Error occurs
output.println(indentNext + "<" + name + ">");
Iterator matchIterator = items.iterator();
while (matchIterator.hasNext()) {
TargetMatch tm = (TargetMatch)(matchIterator.next());
tm.encode(output, indenter);
}
output.println(indentNext + "</" + name + ">");
}
indenter.out();
}
indenter.out();
output.println(indent + "</" + name + "s>");
}
}
堆栈跟踪:
Exception in thread "main" java.lang.ClassCastException: SubjectID_V cannot be cast to java.util.List
at Target_V.encodeSection(Target_V.java:71)
at Target_V.encode(Target_V.java:41)
at com.sun.xacml.AbstractPolicy.encodeCommonElements(Unknown Source)
at com.sun.xacml.PolicySet.encode(Unknown Source)
at PolicyFactory_V.main(PolicyFactory_V.java:56)
最佳答案
List items = (List)(it.next())
仅当您要迭代的 List
仅包含 List< 类型的元素时才有效
(即实现 List
接口(interface)的类的实例)。
根据您收到的错误,您正在尝试将 SubjectID_V
类型的实例转换为 List
。您应该查看初始化该列表的代码。您的错误可能就在那里。
使用通用列表可能会帮助您避免此异常,因为它首先会阻止代码通过编译。
关于尝试迭代列表时抛出 Java ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26777582/