【发布时间】:2012-10-24 19:30:09
【问题描述】:
我有一个抽象类 Vehicle 有 2 个实现的子类 RedVehicle 和 YellowVehicle。
在另一个类中,我有一个 List<Vehicle> 包含两个子类的实例。
我希望能够将一个类类型传递给一个方法,然后使用该类型来决定我想要在List 中对哪组对象执行操作。
由于Class 是通用的,我应该用一些东西对其进行参数化,但是将参数作为父类Vehicle 会停止调用代码的工作,因为exampleMethod 现在需要一种Vehicle,而不是@987654329 的子类@ 或YellowVehicle。
我觉得应该有一种干净的方法来做到这一点,那么实现该功能的正确方法是什么?
n.b.我不一定要传入Class 类型,如果有更好的建议我很乐意尝试。
调用代码:
service.exampleMethod(RedVehicle.class);
service.exampleMethod(YellowVehicle.class);
字段/方法:
//List of vehicles
//Vehicle has 2 subclasses, RedVehicle and YellowVehicle
private List<Vehicle> vehicles;
//Having <Vehicle> as the Class parameter stops the calling code working
public void exampleMethod(Class<Vehicle> type)
{
for(Vehicle v : vehicles)
{
if(v.getClass().equals(type))
{
//do something
}
}
}
【问题讨论】: