实例化中绑定的Java通用参数

时间:2013-05-28 15:34:02

标签: java generics

现在有一个大脑屁。

我有这个:

public static final Map<WorkType, Class> handler;

然后

handler = new TreeMap<WorkType, Class>() {{
    put(WorkType.SUBMIT, UtilityHandler.class);
}};

然后

JobHandler jobHandler = instantiateHandler(handler.get(work), work, buildingId);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!! this shows a warning unchecked assignment
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Unchecked assignment: 'java.lang.Class' to 'java.lang.Class<? extends JobHandler>

然后

@SuppressWarnings(value="unchecked")
private static JobHandler instantiateHandler(Class<? extends JobHandler> ref, WorkType type, String id) {

    if(ref == null) {
        throw new UnsupportedOperationException("This action is not supposed!");
    }

    try {
        Constructor<JobHandler> constructor = (Constructor<JobHandler>) ref.getConstructor(WorkType.class, String.class);
        JobHandler handler = constructor.newInstance(type, id);
        return handler;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
        Utilities.writeLogException(null, e);
    }

    return null;

}

我想摆脱未经检查的任务。我以为我能做到这一点:

public static final Map<WorkType, Class extends JobHandler> handler;

但不允许这样做。有什么想法/建议?感谢。

2 个答案:

答案 0 :(得分:1)

我认为你应该宣布

Map<WorkType, Class<? extends JobHandler>> handler
从方法instantiateHandler中的代码

看起来你期望Class任何子类型的JobHandler对象,并且你试图实例化JobHandler对象

答案 1 :(得分:1)

我想你想要:

Map<WorkType, Class<? extends JobHandler>> handler