我正在将人们的数据转换成压缩形式。所以我有一堆接口:
public interface Brief {}
public interface Detail {}
public interface DetailToBriefConverter<T extends Detail, R extends Brief>  {
    R convert(T detail);
}
,一堆 pojo:
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。
我怎样才能摆脱这个警告,或者我必须忍受它吗?
DetailToBriefConverter detailToBriefConverter = mainApp.map.get(type);
detailToBriefConverter是原始类型:您没有为其提供类型参数。你也没有在地图上给它一个。
鉴于您将异构类型放入映射中,您可以使用的唯一类型参数是<?, ?>:
DetailToBriefConverter<?, ?> detailToBriefConverter = mainApp.map.get(type);
(也将其添加到地图声明中)
But then you've got the problem that you can't invoke detail like this:
detailToBriefConverter.convert(detail);
because the type of the parameter is ?, and you've got an EmployeeDetail, or whatever it is called.
Basically, what you are trying to do isn't type safe. It is possible that you can write the code in such a way that you don't actually get any runtime exceptions; but it's rather brittle.
What you really need is a type-safe heterogeneous container. Look it up in Effective Java or elsewhere.
| 归档时间: | 
 | 
| 查看次数: | 7519 次 | 
| 最近记录: |