Java 抽象、泛型和构建器

标签 java generics

这是我第一次发帖,但我遇到了很多问题。 我目前有一个带有标题的 AbstractDevice 类:

public abstract class AbstractDevice<T extends AbstractDevice.Builder<T>> implements Device

这个类有一个带有标题的嵌套构建器类:

public static abstract class Builder<T>

我还有一个带有标题的 AbstractPeripheral 类:

public abstract class  AbstractPeripheral<T extends AbstractPeripheral.Builder<T>> extends AbstractDevice<AbstractPeripheral.Builder>

这个类也有自己的嵌套构建器类,其标题为:

public static abstract class Builder<T> extends AbstractDevice.Builder<Builder>.

我的目标是让 AbstractPeripheral 扩展 AbstractDevice 并且 AbstractPeripheral 的构建器扩展 AbstractDevice 的。但是,我在尝试编译时收到此错误:

type argument uxb.AbstractPeripheral.Builder is not within bounds of type-variable T.

感谢任何帮助。谢谢 抽象设备:

package uxb;

import java.util.List;
import java.util.Optional;
import java.util.ArrayList;
import java.math.BigInteger;


public abstract class AbstractDevice<T extends AbstractDevice.Builder<T>>     
implements Device{

public static abstract class Builder<T>{

private Integer version;

private Optional<Integer> productCode;

private Optional<BigInteger> serialNumber;

private List<Connector.Type> connectors;

public Builder(Integer version){
  this.version = version;
}  //end constructor method


public T productCode(Integer productCode){
  if(productCode != null){
    this.productCode = Optional.of(productCode); 
  }  //end if statement
  else{
    this.productCode = Optional.empty();
  }  //end else statement
  return getThis();
}  //end method productCode()

public T serialNumber(BigInteger serialNumber){
  if(serialNumber != null){
    this.serialNumber = Optional.of(serialNumber);
  }  //end if statement
  else{
  /*Class has a static field for ZERO value*/
    this.serialNumber = Optional.empty();
  }  //end else statement
  return getThis();
}  //end method serialNumber()


public T connectors(List<Connector.Type> connectors){
 this.connectors = connectors;
 return getThis();
}  //end method connectors


protected abstract T getThis();


protected List<Connector.Type> getConnectors(){
  return connectors;
}  //end method getConnectors()


protected void validate(){
  if(version == null){
    throw new NullPointerException("Cannot be validated");
  }
}  //end method validate()

}  //end nested abstract class Builder


private final Integer version;

private final Optional<Integer> productCode;


private final Optional<BigInteger> serialNumber;

private final List<Connector.Type> connectors;

private final List<Connector> connectorObjects;


protected AbstractDevice(Builder<T> builder){
  this.version = builder.version;
  this.productCode = builder.productCode;
  this.serialNumber = builder.serialNumber;
  this.connectors = builder.connectors;
  ArrayList<Connector> temp = new ArrayList<Connector>();
  for(int i = 0; i < connectors.size(); i++){
    temp.add(new Connector(this, i, connectors.get(i)));
  }  //end for loop
  connectorObjects = temp;
}  //end constructor method



public Optional<Integer> getProductCode(){
return productCode;
}  //end method getProductCode()


public Integer getConnectorCount(){
/*Not Implemented Yet*/
return 0;
}  //end method getConnectorCount()



public Optional<BigInteger> getSerialNumber(){
return serialNumber;
}  //end method getSerialNumber()


public Integer getVersion(){
return version;
}  //end method getVersion()

public List<Connector> getConnectors(){
return new ArrayList<Connector>(connectorObjects);
}  //end method getConnectors()


public Connector getConnector(int index){
  if(! getConnectors().isEmpty()){
  return getConnectors().get(index);
}  //end if statement
else{
  return null;
}  //end else statement
}  //end method getConnector()

} //end abstract class AbstractDevice

抽象外设: 封装uxb;

import java.util.List;

public abstract class  AbstractPeripheral<T extends  
AbstractPeripheral.Builder<T>> extends 
AbstractDevice<AbstractPeripheral.Builder>{

public static abstract class Builder<T> extends 
AbstractDevice.Builder<Builder>{

protected void validate(){
  super.validate();
  if(getConnectors().equals(null)){
    throw new IllegalStateException("Cannot be validated");
  }  //end if statement
  if(checkTypes(getConnectors())){
    throw new IllegalStateException("Cannot be validated");
  }  //end if statement
}  //end method 

private boolean checkTypes(List<Connector.Type> types){
  for(Connector.Type type: types){
    if(type != Connector.Type.PERIPHERAL){
      return false;
    }  //end if statement
  }  //end for each loop
  return true;
}  //end method checkTypes

public Builder(Integer version){
  super(version);
}  //end constructor method
}  //end nested class Builder

public AbstractPeripheral(Builder<T> builder){
 super(builder);
} 
}  //end class AbstractPeripheral

中心: 封装uxb;

public class Hub extends AbstractDevice<Hub.Builder>{

  public static class Builder extends AbstractDevice.Builder<Builder>{

public Builder(Integer version){
  super(version);
} //end constructor method

public Hub build(){
 validate();
 return new Hub(getThis());
}  //end method build()

protected Builder getThis(){
  return this;
} //end method getThis()

protected void validate(){
  super.validate();
  if(!(super.getConnectors().contains(Connector.Type.COMPUTER))){
    throw new IllegalStateException("Cannot be validated");
  }  //end if statement\
  if(!(super.getConnectors().contains(Connector.Type.PERIPHERAL))){
    throw new IllegalStateException("Cannot be validated");
  }  //end if statement
}  //end validate()
}  //end nested class Builder

private Hub(Builder builder){
super(builder);
}  //end constructor method

public DeviceClass getDeviceClass(){
return DeviceClass.HUB;
}  //end method getDeviceClass()


}  //end class Hub

最佳答案

您确实需要使用正在构建的类,构建器作为构建器的参数。然而,正在构建的对象不需要需要了解构建器,因此不需要它作为参数。

我在几个开源项目中使用了这种模式或略有不同,包括 Apache Brooklyn和jclouds。

因此,从您的示例中,更改父类如下:

public abstract class AbstractDevice implements Device {
    public static abstract class Builder<T, B> {
        public abstract B self();
        public abstract T build();
        public B example(String value) {
            // do something with value
            return self();
        }
    }
}

请注意,我还添加了一个抽象的 build() 方法,它将返回构建的对象。 self() 方法是必需的,因为当构建器方法返回 this 时,它将具有错误的类型。相反,每个构建器方法必须以 return self(); 结尾,如所示的 example(String value) 方法中所示。那么 child 就变成了:

public abstract class AbstractPeripheral extends AbstractDevice {
    public static abstract class Builder<T, B> extends AbstractDevice.Builder<T, B> {
    }
}

您可以看到,TB 泛型参数分别用于指向类的类型和构建器的类型。因此,要创建一个使用这些的具体类,应该创建类似这样的内容:

public class Hub extends AbstractPeripheral {
    public static class Builder extends AbstractPeripheral.Builder<Hub, Builder> {
        public static final Builder builder() {
            return new Builder();
        }
        public Builder self() {
            return this;
        }
        public Hub build() {
            return new Hub();
        }
    }
}

这还有一个静态 builder() 方法,它返回正确的 Builder 类的实例,如果您愿意,您也可以直接调用构造函数。 build() 方法只是创建并返回具体类,self() 方法在此处实现以返回 this 将具有正确的类型。

将所有内容放在一起,我们可以使用它来创建一个 Hub 对象,如下所示:

Hub hub = Hub.Builder.builder()
        .example("something")
        .build();

请注意,AbstractDevice.Builder#example(String) 方法返回正确的类型,因为它实际上调用 Hub#self()build() 按预期返回 Hub 的具体实例。

要减轻一些痛苦并删除重复的样板,您还可以尝试使用 Google AutoValue项目,我们现在正在 jclouds 中切换到该项目。

关于Java 抽象、泛型和构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560266/

相关文章:

java - 将 xpath 从 String 转换为 WebElement

java - 在 Parse 后端查找当前时间和上次更新时间之间的差异

c# - 如何将委托(delegate)存储在列表中

java - 将继承类分配给继承接口(interface)时出现不兼容类型错误

java - 状态栏什么时候隐藏?

java - 如何在没有数据库的情况下创建 jasper 报告

Java 实例化新的 Map.Entry-array

Scala Generics - ADT 中的通用提取器方法

java - jhipster-如何添加新角色

java - 将 Class.forName ("java.lang.String")/'Class.forName("some_str_var")' 转换为 Class<String> : why former produces unchecked compiler warning?