我對Java很新,我主要是PHP/JavaScript開發人員多年。我現在的任務是用java重寫我的一個PHP應用程序,而我被困在一個讓我瘋狂的部分。快速瀏覽問題:我有兩種不同類型的「回覆」對象,我創建了一個接受他們兩個的類。然後我需要能夠遍歷它們並檢查它們中的方法。很難解釋,但我會以代碼進行非常簡單的版本...通過泛型訪問類的方法對象類型
public class A {
private Boolean success;
private Map<String, ? extends Object> prop;
public A() {}
public boolean getSuccess() {
boolean succeed = true;
for(Map.Entry<String, ? extends Object> result : prop.entrySet()) {
String type = result.getKey();
Object response = result.getValue();
//I need to access the method getSuccess() in AResult or BResult here, but cannot. Why? and How?
/*
if(!response.getSuccess()) {
succeed = false;
}*/
}
return succeed;
}
public void addResult(String type, BResult result) {
prop.add(type, result);
}
public void addResult(String type, AResult result) {
prop.add(type, result);
}
}
public class AResult {
private Boolean success;
private String type;
public AResult(String type, Boolean success) {
this.type = type;
this.success = success;
}
public boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class BResult {
private Boolean success;
private String type;
public BResult(String type, Boolean success) {
this.type = type;
this.success = success;
}
public boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
現在,下面給出我怎麼能訪問.getSuccess()每個結果類型的內環路按照A→
A me = new A();
me.addResult(new AResult("rate", true));
me.addResult(new BResult("label", false));
if(me.getSuccess()) {
//yay things went well;
} else {
//boo things went bad;
}
我絕對必須有Aresult和BResult,我不能改變。在A的getSuccess()方法中,它不允許我訪問AResult和BResult類的getSuccess(),並且我不能強制類型,因爲它可能是AResult或BResult。
我想過嘗試類似的東西....
if(response instaceof AResult) {
AResult res = (AResult) result;
//...
} else if(response instanceof BResult) {
BResult res = (BResult) result;
//...
}
但是如果我們決定增加一個新的類型,像CResult或不管它會使代碼無法使用,我可以用一個巨大的結束如果elseif語句嘗試確定正確的類型只是爲了訪問其內部的simgle方法,那麼混亂。 我在這一個嚴重丟失,任何人可以提供幫助將不勝感激。非常感謝您的參與。