Insecure generation during collection deserialization

public Configuration(Node node, File file) {
    HashMap<String, String> conf = (HashMap<String, String>) SerializationUtils.deserialize(new FileInputStream(file));
}

I understand why this gives an unsafe throw warning, but what is the best / acceptable way to do this safely? Is there a good way?

+5
source share
3 answers

You cannot handle this situation in a completely safe way using only the Java language.

Since this is something that needs to be done multiple times, and you cannot get around it, I suggest using the genre method to read and transfer generic objects:

@SuppressWarnings("unchecked")
public static <T> T readObject(
    ObjectInputStream in
) throws IOException, ClassNotFoundException {
    return (T)in.readObject();
}

However, I suggest that you usually not use such methods to suppress valid warnings.

+2
source

, , (.. String), (.. ) , . , - - "checker" :

Map<?,?> conf = deserialize(rsrc);
Map<String, String> checked = checkMap(conf, String.class, String.class);
//can use checked freely

:

@SuppressWarnings("unchecked")
public static <K, V> Map<K,V> checkMap(Map<?,?> map, Class<? extends K> k, Class<? extends V> v) {
    for (Map.Entry<?, ?> e : map) {
        k.cast(e.getKey());   //will throw ClassCastException
        v.cast(e.getValue());
    }
    return (Map<K,V>) map; //unchecked 
}
+2

, . , . , , - , . , , .

public static <T> T readObject(
    ObjectInputStream in
) throws IOException, ClassNotFoundException {
    @SuppressWarnings("unchecked")
    T val = (T)in.readObject();
    return val;
}

, ( , ).

+1

All Articles