删除警告(类型安全:未经检查的 capture#2-of 转换?将模板扩展到 T)

Removing Warnings (Type safety: Unchecked cast from capture#2-of ? extends Template to T)

在我的 IF 中,所有 3 行都有警告。我怎样才能在不压制的情况下将其删除?有更好的解决方案吗?

public void template() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        if(templateResult == null){
            Class templateClass = getGenericTypeArgument(this.getClass(), 0);
            Constructor<? extends Template> constructor = templateClass.getConstructor(new Class[]{List.class, List.class});
            templateResult = (T) constructor.newInstance(listData, listaDataRes);       
        }
    }

您可以通过不使用 raw types:

来删除其中的一些
Class<?> templateClass = getGenericTypeArgument(this.getClass(), 0);
//    ^
Constructor<? extends Template> constructor =
    templateClass.getConstructor(new Class<?>[]{List.class, List.class});
//                                         ^

在我看来,您无法避免对 T.

进行未经检查的强制转换

Is there a better solution?

在我看来,您可能正在使用 getGenericSuperclass().getActualTypeArguments() 东西,您可以通过将 Class<T> 作为参数传递给对象 (shown here) 来移除所有警告。