I have an abstract class Vehicle
with 2 implemented subclasses RedVehicle
and YellowVehicle
.
In another class I have a List
Do this instead:
public <T extends Vehicle> void exampleMethod(Class<T> type)
Why don't you use the visitor pattern?
That way you
if(v.getClass().equals(type))
)In detail:
your abstract class Vehicle
gets a method accept(Visitor v)
, with the subclasses implementing it by calling the appropriate method on v
.
public interface Visitor {
visitRedVehicle(RedVehicle red);
visitYellowVehicle(YellowVehicle yellow);
}
Using a visitor:
public class Example {
public void useYellowOnly() {
exampleMethod(new Visitor() {
visitRedVehicle(RedVehicle red) {};
visitYellowVehicle(YellowVehicle yellow) {
//...action
});
}
public void exampleMethod(Visitor visitor){
for(Vehicle v : vehicles) {
v.accept(visitor);
}
}
}