1 回答

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
問題是您Class在服務(wù)定義中使用原始類型。要解決此問題,您可以使用有界通配符類型 ?,如下所示:
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);
}
}
對(duì)于課堂來說,BusinessService事情會(huì)變得更加棘手。首先,有必要制定compareVitamins一個(gè)通用方法來確保兩個(gè)水果屬于同一類型。但即使那樣,我也不相信你可以避免 unchecked cast from the result,getFruitCheckService因?yàn)椋捎贔ruitServices必須處理不同類型水果的服務(wù),你不能為 的返回值提供精確的類型參數(shù)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);
}
}
添加回答
舉報(bào)