我最近遇到了一个有趣的问题:我希望泛型类中的方法只接受指定泛型类型 的内部类的实例。以下示例中说明的目标是CarInspector<CarBrand1>
只能检查由CarBrand1
制造的驱动轮,同时保持DrivingWheel
内部CarMaker
级。理由是我不希望DrivingWheel
在封闭的CarMaker
子类之外定义。
这是我解决问题的第一步:
public abstract class CarMaker {
public abstract class DrivingWheel {}
}
public class CarBrand1 extends CarMaker {
public class DrivingWheelByCarBrand1 extends DrivingWheel {}
private final DrivingWheelByCarBrand1 drivingWheel = new DrivingWheelByCarBrand1();
public DrivingWheelByCarBrand1 getDrivingWheel() {
return drivingWheel;
}
}
public class CarBrand2 extends CarMaker {
private class DrivingWheelByCarBrand2 extends DrivingWheel {}
private final DrivingWheelByCarBrand2 drivingWheel = new DrivingWheelByCarBrand2();
public DrivingWheelByCarBrand2 getDrivingWheel() {
return drivingWheel;
}
}
public class CarInspector<T extends CarMaker> {
public void inspect(T.DrivingWheel arg) {}
}
但是,以下代码编译得很好:
CarBrand1 c1 = new CarBrand1();
CarBrand2 c2 = new CarBrand2();
CarInspector<CarBrand1> carInspector = new CarInspector<>();
carInspector.inspect(c1.getDrivingWheel());
carInspector.inspect(c2.getDrivingWheel());
有没有办法让编译器在行carInspector.inspect(c2.getDrivingWheel())
中抛出错误或警告?
注意:这个问题除了提议的设计可能不是最佳选择,将DrivingWheel
定义为DrivingWheel<T extends CarMaker>
可能更明智的事实;尽管如此,这是一个有趣的切线,它是我正在考虑的特定领域的设计选择。
答案 0 :(得分:2)
您需要使用更多泛型。更改基础DrivingWheel
类以添加指定汽车品牌的通用参数:
public class CarInspector<T extends CarMaker> {
public void inspect(DrivingWheel<T> arg) {}
}
答案 1 :(得分:1)
我已经能够通过将班级CarInspector
更改为:
public class CarInspector<T extends CarMaker, U extends CarMaker.DrivingWheel> {
public void inspect(U drivingWheel) {}
}
然后:
CarInspector<CarBrand1, DrivingWheelByCarBrand1> carInspector = new CarInspector<>();
但是,我不知道是否有更好的方法来做到这一点......