Java 方法泛型与类泛型的绑定限制
我正在尝试创建一个有点强的类型化API:Java 方法泛型与类泛型的绑定限制,java,generics,Java,Generics,我正在尝试创建一个有点强的类型化API: 类属性类型{…} 类子类型1扩展了PropertyType{…} 类子类型2扩展了PropertyType{…} 类PropertyHandler必须将getValue()的返回类型添加到PropertyHandler的通用签名中。否则,PropertyHandler无法从PropertyType的泛型定义推断getValue()返回类型 因此,要么将返回类型和属性类型分配给PropertyHandler通用签名,要么通过在PropertyHandler
类属性类型{…}
类子类型1扩展了PropertyType{…}
类子类型2扩展了PropertyType{…}
类PropertyHandler必须将getValue()
的返回类型添加到PropertyHandler
的通用签名中。否则,PropertyHandler
无法从PropertyType
的泛型定义推断getValue()
返回类型
因此,要么将返回类型和属性类型分配给PropertyHandler
通用签名,要么通过在PropertyHandler
中指定返回类型来翻转它,并使用PropertyHandler
确保正确的PropertyType
参数类型,如下所示:
class PropertyType<T, H extends PropertyHandler<T>> {
public T getValue() { ... }
}
class IntegerType extends PropertyType<Integer, PropertyHandler<Integer>> { ... }
class BooleanType extends PropertyType<Boolean, PropertyHandler<Boolean>> { ... }
class PropertyHandler<V> {
public <T extends PropertyType<V, PropertyHandler<V>>> V getValue(T prop) {
return prop.getValue();
}
}
类属性类型{
公共T getValue(){…}
}
类IntegerType扩展PropertyType{…}
类BooleanType扩展了PropertyType{…}
类属性句柄{
公共价值(T道具){
返回prop.getValue();
}
}
以下是您将如何使用它:
PropertyHandler<Integer> ph = new PropertyHandler<>();
IntegerType p1 = new IntegerType();
Integer v1 = ph.getValue(p1); // works fine
BooleanType p3 = new BooleanType();
Boolean v3 = ph.getValue(p3); // compile time error
PropertyHandler ph=newpropertyHandler();
IntegerType p1=新的IntegerType();
整数v1=ph.getValue(p1);//很好
BooleanType p3=新的BooleanType();
布尔值v3=ph.getValue(p3);//编译时错误
我不确定我是否正确理解了这个问题,但您能否更改“class Property Handler”是的,确实如此。但是您的建议不起作用:“class Property Handler”“这不会编译,直到您还指定了X作为类型变量,这不是我想要的…为什么您不想让X成为类型变量?我必须声明“class PropertyHandler”,然后在创建实例时定义X。”。因为我的类层次结构比较复杂,所以我有一个例子“class SpecialProp Extendes PropertyType{…}”,我想将我的getValue方法绑定到SpecialProp而不限制T。谢谢你的建议。通过这样做,它将允许将PropertyHandler的使用限制为某种类型的数据(即Integer),而不是类型(即IntegerType)。我编辑了我的原始帖子,在子类中包含了一些泛型。