Eclipse is giving me a warning of the following form:
Type safety: Unchecked cast from Object to HashMap
This is from a call to
Here is a shortened example that avoids the "unchecked cast" warning by employing two strategies mentioned in other answers.
Pass down the Class of the type of interest as a parameter at runtime (Class
). Then you can use: inputElementClazz.cast(anyObject);
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
).
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);