我正在将人们的数据转换为简明格式。所以我有很多接口:
public interface Brief {}
public interface Detail {}
public interface DetailToBriefConverter<T extends Detail, R extends Brief> {
R convert(T detail);
}
,一堆pojos:
public class StudentBrief implements Brief {...}
public class StudentDetail implements Detail {...}
public class EmployeeBrief implements Brief {...}
public class EmployeeDetail implements Detail {...}
和转换器:
public class StudentDetailToBriefConverter implements DetailToBriefConverter<StudentDetail, StudentBrief> {
@Override
public StudentBrief convert(StudentDetail detail) {
// logic here
}
}
等
我的主班大概是这样的:
public class MainApp {
private Map<String, DetailToBriefConverter> map = ImmutableMap.<String, DetailToBriefConverter>builder()
.put("employee", new EmployeeDetailToBriefConverter())
.put("student", new StudentDetailToBriefConverter())
.build();
public static void main(String[] args) {
MainApp mainApp = new MainApp();
String type = "employee"; // comes from the request actually
Detail detail = new EmployeeDetail(); // comes from the request
DetailToBriefConverter detailToBriefConverter = mainApp.map.get(type);
detailToBriefConverter.convert(detail);
}
}
这可行,但是我收到警告unchecked call to convert(T) as a member of a raw type DetailToBriefConverter
。
如何摆脱这个警告,或者我必须忍受它?
答案 0 :(得分:4)
DetailToBriefConverter detailToBriefConverter = mainApp.map.get(type);
detailToBriefConverter
是原始类型:您没有为其提供类型参数。您也没有在地图上给它一个。
鉴于您要将异构类型放入地图中,因此唯一可以使用的类型参数是<?, ?>
:
DetailToBriefConverter<?, ?> detailToBriefConverter = mainApp.map.get(type);
(也将其添加到地图声明中)
但是随后您遇到了无法像这样调用detail
的问题:
detailToBriefConverter.convert(detail);
因为参数的类型为?
,并且您有一个EmployeeDetail
或其他名称。
基本上,您尝试执行的操作类型不安全。您可能会以实际上没有任何运行时异常的方式编写代码。但是它很脆。
您真正需要的是类型安全的异构容器。在有效的Java 或其他地方查找它。
答案 1 :(得分:0)
将方法声明更改为
public interface DetailToBriefConverter<T extends Detail, R extends Brief> {
Brief convert(Detail detail);
}
在声明了DetailToBriefConverter的地方,将其声明为DetailToBriefConverter
public class MainApp {
private Map<String, DetailToBriefConverter<? extends Detail, ? extends Brief>> map = ImmutableMap.<String, DetailToBriefConverter<? extends Detail, ? extends Brief>>builder()
.put("employee", new EmployeeDetailToBriefConverter())
.put("student", new StudentDetailToBriefConverter())
.build();
public static void main(String[] args) {
MainApp mainApp = new MainApp();
String type = "employee"; // comes from the request actually
Detail detail = new EmployeeDetail(); // comes from the request
DetailToBriefConverter<? extends Detail, ? extends Brief> detailToBriefConverter = mainApp.map.get(type);
detailToBriefConverter.convert(detail);
}
}
基本上,在声明类时,需要指定类型,否则会收到原始类型警告