[英]How to bind value of type parameter to type of `this`?
interface A<T extends B</*?*/>> {
method(T param);
}
interface B<U extends A> {
// ...
}
In code snippet above how can it be expressed that method A#method
should only accept parameters that are objects parametrized by type (or its descendants) on which the method is called. 在上面的代码片段中,如何表达方法
A#method
应仅接受参数,这些参数是根据调用该方法的类型(或其后代)进行参数化的对象。
I'd like to achive something like this: 我想要达到以下目的:
interface Vehicle<T extends SteeringDevice</*?*/> {
default steer(T steeringDevice) {
// ...
}
}
interface SteeringDevice<U extends Vehicle> {
// ...
}
// -----
class Car implements Vehicle<SeeringWheel> {
// ...
}
class SteeringWheel implements SteeringDevice<Car> {
// ...
}
// -----
class Bike implements Vehicle<Handlebars> {
// ...
}
class Handlebars implements SteeringDevice<Bike> {
// ...
}
... where it's possible so safely call new Car().steer(new SteeringWheel())
but not new Car().steer(new Handlebars())
. ...在可能的情况下,安全地调用
new Car().steer(new SteeringWheel())
而不是new Car().steer(new Handlebars())
。
I think this does what you want: 我认为这可以满足您的需求:
interface Vehicle<T extends SteeringDevice<? extends Vehicle<T>>> {
default void steer(T steeringDevice) {}
}
interface SteeringDevice<U extends Vehicle<? extends SteeringDevice<U>>> {
// ...
}
This forces the two compatible implementations to cross-reference each other. 这迫使两个兼容的实现相互交叉引用。 Changing the argument to an incompatible type will now trigger a compile error in the paired class.
现在,将参数更改为不兼容的类型将在配对的类中触发编译错误。
One potential issue with the above is that it allows for multiple implementations of SteeringDevice<Car>
. 上面的一个潜在问题是,它允许
SteeringDevice<Car>
多种实现。 You can make the pairing more explicit by adding a self type parameter: 您可以通过添加自类型参数使配对更加明确:
interface Vehicle<U extends Vehicle<U, T>, T extends SteeringDevice<T, U>> {
default void steer(T steeringDevice) {}
}
interface SteeringDevice<T extends SteeringDevice<T, U>, U extends Vehicle<U, T>> {
// ...
}
class Car implements Vehicle<Car, SteeringWheel> {
// ...
}
class SteeringWheel implements SteeringDevice<SteeringWheel, Car> {
// ...
}
It's still possible to create another implementation of SteeringDevice<SteeringWheel, Car>
, because Java doesn't have a true self type, but at least it makes the violation more obvious. 仍然可以创建
SteeringDevice<SteeringWheel, Car>
另一个实现,因为Java没有真正的自身类型,但是至少它使违规更加明显。 It also has the advantage of breaking both classes on an invalid type argument. 它还具有打破无效类型参数上的两个类的优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.