1 回答
TA贡献1765条经验 获得超5个赞
问题是您Class在服务定义中使用原始类型。要解决此问题,您可以使用有界通配符类型 ?,如下所示:
class FruitServices {
private Map<Class<? extends Fruit>, FruitCheckService<? extends Fruit>> beansMap;
public FruitServices(List<FruitCheckService<? extends Fruit>> fruitCheckServices) {
beansMap = new HashMap<>();
fruitCheckServices
.forEach(
fruitCheckService -> {
Class<? extends Fruit> implementation = fruitCheckService.getImplementation();
beansMap.put(implementation, fruitCheckService);
}
);
}
public FruitCheckService<? extends Fruit> getFruitCheckService(Class<? extends Fruit> clazz) {
return beansMap.get(clazz);
}
}
对于课堂来说,BusinessService事情会变得更加棘手。首先,有必要制定compareVitamins一个通用方法来确保两个水果属于同一类型。但即使那样,我也不相信你可以避免 unchecked cast from the result,getFruitCheckService因为,由于FruitServices必须处理不同类型水果的服务,你不能为 的返回值提供精确的类型参数getFruitCheckService。
class BusinessService {
private FruitServices fruitServices;
public <T extends Fruit> void compareVitamins(T one, T two) {
@SuppressWarnings("unchecked")
FruitCheckService<T> fruitCheckService =
(FruitCheckService<T>) fruitServices.getFruitCheckService(one.getClass());
List<String> result = fruitCheckService.compareVitaminsFromDifferentCountries(one, two);
}
}
添加回答
举报