我对 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;
}
}
现在,考虑到以下情况,我如何访问 A 中循环内每个结果类型的 .getSuccess()?
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 或其他任何类型,它会导致该代码无法使用,并且我最终可能会得到一大堆 if elseif 语句,试图确定正确的类型只是为了访问内部的 simgle 方法它的。 我对此感到非常困惑,任何人都可以提供的帮助将不胜感激。非常感谢您抽出宝贵的时间。
最佳答案
1.创建接口(interface):
interface Result {
boolean getSuccess();
}
2.在 AResult
中实现它和BResult
:
public class AResult implements Result {
// ...
3.制作prop
一个Map<String, Result>
现在,您可以使用Result
作为 prop
中事物的类型,并且自 Result
有getSuccess
,就可以使用了。
您可以使用 AResult
的基类和BResult
extend
,而不是接口(interface);或者您可以选择同时使用两者以获得最大的灵 active ,其中基类实现 Result
但是是abstract
.
从根本上来说:
如果事物具有共同特征,请为这些特征创建一个接口(interface)。
如果您想分享这些共同特征的实现,可以:
使用类
extend
的基类(继承)将这些特征隔离到它们自己的类中,然后在
AResult
中使用这些类。和BResult
(这称为组合或聚合)
关于java - 通过泛型对象类型访问类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38934690/