我正在从事一个需要将服务添加到组件的项目。 Service
类是一个没有任何方法的接口(interface)。这是我的服务如何工作的示例:
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);
我正在寻找一种方法来指定 service
需要实现(扩展)task
并且 task
正在扩展服务
接口(interface),像这样(不编译):
<T extends Service> addService(T service, Class<? super T extends Service> task);
最佳答案
我认为 <T extends Service, S extends T> void addService(S service, Class<T> clazz)
听起来它符合您的标准:
public static class Foo {
public interface Service { }
public interface CarWash extends Service {
void washCar();
}
public interface CarRepair extends Service {
void repairCar();
}
static <T extends Service, S extends T> void addService(S service, Class<T> clazz) {}
public static void main(String[] args) {
addService(null, CarWash.class); // Fine.
addService(null, Object.class); // Compilation error.
}
}
(我添加了一些静态变量并从方法签名中删除了 Car
,因为我没有要编译的定义)
关于java - "extends"和 "super"的泛型通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29451541/