我对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方法,那么混乱。 我在这一个严重丢失,任何人可以提供帮助将不胜感激。非常感谢您的参与。