我正在开发一个需要将服务添加到组件的项目。 Service
类是没有任何方法的接口。以下是我的服务如何工作的示例:泛型与“扩展”和“超级”的通配符
public interface Service { }
public interface CarWash extends Service {
void washCar(Car car);
}
public interface CarRepair extends Service {
void repairCar(Car car);
}
现在这些服务有很多实现。单个类可以实现多个服务,因为这车库类:
public class Garage implements CarWash, CarRepair {
@Override
public void washCar(Car car) { /* .. */ }
@Override
public void repairCar(Car car) { /* .. */ }
}
当添加到组件服务,我不希望需要使用该服务的所有任务,但例如使用Garage
仅洗车(CarWash
)但不能修理(CarRepair
)。因此我指定的任务类,就像这样:
void addService(Service service, Class<? extends Service> task);
要检查服务是否可以真正执行的任务,我使用泛型:
<T extends Service> addService(T service, Class<? super T> task);
这种运作良好,但不检查提供的任务实际上是一个任务(实现Service
类),所以这会工作:
addService(myTask, Object.class);
我正在寻找一种方法符合规范IFY是service
需要实现(延长)的task
和task
是扩展Service
接口,这样(不编译):
<T extends Service> addService(T service, Class<? super T extends Service> task);
如何:' void addService(S服务,类 clazz);'? –
2015-04-04 21:39:12