How do I address unchecked cast warnings?

后端 未结 23 1181
醉梦人生
醉梦人生 2020-11-22 03:06

Eclipse is giving me a warning of the following form:

Type safety: Unchecked cast from Object to HashMap

This is from a call to

23条回答
  •  礼貌的吻别
    2020-11-22 03:43

    Here is a shortened example that avoids the "unchecked cast" warning by employing two strategies mentioned in other answers.

    1. Pass down the Class of the type of interest as a parameter at runtime (Class inputElementClazz). Then you can use: inputElementClazz.cast(anyObject);

    2. For type casting of a Collection, use the wildcard ? instead of a generic type T to acknowledge that you indeed do not know what kind of objects to expect from the legacy code (Collection unknownTypeCollection). After all, this is what the "unchecked cast" warning wants to tell us: We cannot be sure that we get a Collection, so the honest thing to do is to use a Collection. If absolutely needed, a collection of a known type can still be built (Collection knownTypeCollection).

    The legacy code interfaced in the example below has an attribute "input" in the StructuredViewer (StructuredViewer is a tree or table widget, "input" is the data model behind it). This "input" could be any kind of Java Collection.

    public void dragFinished(StructuredViewer structuredViewer, Class inputElementClazz) {
        IStructuredSelection selection = (IStructuredSelection) structuredViewer.getSelection();
        // legacy code returns an Object from getFirstElement,
        // the developer knows/hopes it is of type inputElementClazz, but the compiler cannot know
        T firstElement = inputElementClazz.cast(selection.getFirstElement());
    
        // legacy code returns an object from getInput, so we deal with it as a Collection
        Collection unknownTypeCollection = (Collection) structuredViewer.getInput();
    
        // for some operations we do not even need a collection with known types
        unknownTypeCollection.remove(firstElement);
    
        // nothing prevents us from building a Collection of a known type, should we really need one
        Collection knownTypeCollection = new ArrayList();
        for (Object object : unknownTypeCollection) {
            T aT = inputElementClazz.cast(object);
            knownTypeCollection.add(aT);
            System.out.println(aT.getClass());
        }
    
        structuredViewer.refresh();
    }
    

    Naturally, the code above can give runtime errors if we use the legacy code with the wrong data types (e.g. if we set an array as the "input" of the StructuredViewer instead of a Java Collection).

    Example of calling the method:

    dragFinishedStrategy.dragFinished(viewer, Product.class);
    

提交回复
热议问题