简体   繁体   中英

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. However this class generates a warning on unchecked cast on line 39 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<?> . 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()); 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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