简体   繁体   English

在return语句中对未选中的强制转换进行警告

[英]warning on unchecked cast on a return statement

I have a class that holds a set of Valueloaders that handle values of type T. This is how I have created the class. 我有一个类,它包含一组处理类型为T的值的Valueloader。这就是我创建类的方法。 However this class generates a warning on unchecked cast on line 39 return (ValueLoader<T>) loader; 但是这个类在第39行return (ValueLoader<T>) loader;上的未经检查的强制转换时生成警告return (ValueLoader<T>) loader;

I would like to know if there is way to clean this warning. 我想知道是否有办法清理这个警告。 Here is my code. 这是我的代码。

public enum ValueLoaderRegistry {

REGISTRY;

private transient Map<Class<?>, ValueLoader<?>> map = new HashMap<Class<?>, ValueLoader<?>>();

private ValueLoaderRegistry() {
    initialize();
}

private void initialize() {
    map.put(Integer.class, new IntegerValueLoader());
    map.put(String.class, new StringValueLoader());
    map.put(Double.class, new DoubleValueLoader());
    map.put(Boolean.class, new BooleanValueLoader());
    map.put(Regions.class, new RegoinsValueLoader());

}



@SuppressWarnings("unchecked")
public <T> ValueLoader<T> getLoader(Class<T> key){
    //Suppress unchecked cast warning, as by design we are making sure that 
    //the map contains the objects with right cast. 
    ValueLoader<?> loader = map.get(key);
    return (ValueLoader<T>) loader;
}

} }

There is not a clean way (as in - you're going to need an unchecked cast), since map.values() contains ValueLoader<?> . 由于map.values()包含ValueLoader<?> ,因此没有一种干净的方式(因为 - 你需要一个未经检查的map.values() However, you know by construction of the map that the cast is safe, so it is OK to suppress the warning. 但是,通过构建地图可以知道演员阵容是安全的,因此可以取消警告。

You might want to make doubly sure that the cast is safe by construction by adding a method like this, rather than adding elements directly to the map: 您可能希望通过添加这样的方法来确保构建是安全的,而不是直接向地图添加元素:

private <T> void safePut(
    Map<Class<?>, ValueLoader<?>> map,
    Class<T> clazz,
    ValueLoader<T> valueLoader) {
  map.put(clazz, valueLoader);
}

which prevents you from writing map.put(Integer.class, new StringValueLoader()); 这会阻止你编写map.put(Integer.class, new StringValueLoader()); accidentally. 偶然。

You also might consider doing the cast on the local variable, which would allow you to suppress on just that variable, rather than the entire method: 您还可以考虑对局部变量进行强制转换,这样您就可以仅仅抑制该变量,而不是整个方法:

@SuppressWarnings("unchecked")
ValueLoader<T> loader = (ValueLoader<T>) map.get(key);
return loader;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM