我已經閱讀了關於類拋出異常的這些頁面上的其他一些問題,並且我想確定我的問題基本上是相同的事情(即涉及到不知道約束運行期間類的類型與編譯期間的類型相比)。瞭解java返回語句中的類拋出異常
所以這裏是我的測試類....
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的對象。
如果您需要更多信息,請詢問(如果您願意,我甚至可以發送我的圖書館副本)。
大衛
坦率地說,我不明白你的問題。你已簡化了代碼,但更加複雜了你的解釋:) – Kris
@Krishnanunni事實上,我只是試圖成爲一名有幫助的人,所以其他人會意識到我已經陷入了更復雜一點的情況,以防這個'做作'的例子與我有些關係(也就是說,構建器類實際上是從另一個包中調用的,並且在我的JUnit測試過程中出現了這個問題 - 所以+1需要測試!)另外,我想確認我的理解正確,認爲我理解的時候我不'以我的經驗來看,t有可能在後來消失。不過,我還需要學會「繼續下去」(即理解C語言中的指針)。 – DaveM