
[英]Can a parent class have a field, whose generic type is that of the current descendant?
[英]Generic class whose field with the generic type migth be null
我需要创建一个 class ,我计划在每个操作结束时返回一个实例。 这是 class 及其字段:
public class OperationResult<T> {
private OperationStatus status;
private String message;
private T data;
public OperationResult(OperationStatus status, T data, String message) {
this.status = status;
this.data = data;
this.message = message;
}
public OperationResult(OperationStatus status, String message) {
this.status = status;
this.message = message;
}
}
如您所见,有 2 个构造函数:一个需要 T 数据,一个不需要。 这是因为某些操作提供了一些详细信息以及状态和消息,而其他操作则不提供。 现在,看看下面的方法,它可能返回不同类型的 OperationResult 实例:
OperationResult getCustomerCurrentBalance(int customerId){
if(a<0){
return new OperationResult(OperationStatus.FAIL,"Invalid customer id passed");//No data
}
Customer customer = getCustomerById(customerId);
if(!customer.isActive()){
return new OperationResult(OperationStatus.FAIL,customer,"Customer is not active");//OperationResult<Customer> is returned
}
BigDecimal balance = getCustomerBalance(customerId);
return new OperationResult(OperationStatus.SUCCESS,balance,null);//OperationResult<BigDecimal> is returned
}
如您所见,我无法将方法的返回类型设置为 OperationResult class ,因为实际上可能会返回不同的版本。 如果我这样离开它,编译器不会抱怨,但另一方面,参数化 class 的原始使用并不好。 话虽如此,您对此有任何想法吗? 也许我在这个特定要求中尝试使用 generics 的方式不对?
如果您没有找到更好的解决方案,我建议您尝试使用 inheritance。
class OperationResult {
protected OperationStatus status;
protected String message;
public OperationResult(OperationStatus status, String message) {
this.status = status;
this.message = message;
}
}
class SpecificOperationResult<T> extends OperationResult {
private T data;
public SpecificOperationResult(OperationStatus status, T data, String message) {
super(status, message);
this.data = data;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.