我已经在这些页面上读到了许多关于类类型转换异常的其他问题,我想确保我的问题本质上是相同的(即与在运行时与编译时相比不知道类的绑定类型有关)。
这是我的测试类..。
public class testCastReturn{
public test(){
HashSet<String> StringHash; //a simple hash set
HashMap(<String, ComplexObject> ObjectInfo; //the String value is the name of the complexObject, and complexObject has multiple members (in this instance it is a java model for a database field so it has info pertaining to Key, size etc)
//create a ComplexObject here
addToObjectInfo(aComplexObject); // add it into the HashMap
//repeat above a number of times....
//now collect the 'names' of those objects
StringHash = getObjectKeys();
}
public void addToObjectInfo(complexObject c){
//put a complex object into the HashMap
ObjectInfo.put(c.getNameID, c); //create a set of key value pairs where the name of the object is the key to get the actual object
}
public HashSet<String> getObjectKeys(){
//retrieve the keys only
return HashSet<String> this.ObjectInfo.keySet(); //fails with classCastException
//this however works
HashSet<String> temp = new HashSet<String>(this.ObjectInfo.keySet());
return temp;
}
}//end class如果我的理解是正确的,这就是为什么我可以用这两种形式编译我的代码,但我只能在显式创建临时位置来保存键集的地方运行代码,因为在运行时,JVM不能保证ComplexObject中键的绑定类型。请记住,这是人为设计的版本,所以可能过度简化了它,在我的实际代码中,我使用了一个“构建器”,然后将信息传递给“最终”的类,然后这些类中的一堆被保存在具有ComplexObjects的HashMap的第三个对象中。
如果您需要任何进一步的信息,请询问(如果您愿意,我甚至可以发送我的库的副本)。
大卫
发布于 2012-05-23 20:46:41
public Set<String> getObjectKeys(){
return this.ObjectInfo.keySet();
}这对你有用吗?
https://stackoverflow.com/questions/10720117
复制相似问题