I have a class
class Property<T> {
value T;
public void setValue(T value) {
this.value = value;
}
}
Now I have a list List<Property<?>> properties
with various properties of various Types. I loop through this list and want to set the value of every Property. Therefore I need to cast the generic Property to the correct type like:
e.g. for Integer:
if (property.getType().equals("Integer")) {
Property<Integer> propInt = (Property<Integer>) property;
propInt.setValue((Integer) values[i++]);
}
where values[]
is an Object array which holds the values that I want to set.
Everything works fine, but Java complains about Type Safety "Unchecked cast from Property<?>
to Property<Integer>
". A check like
if (property instanceof Property<Integer>){...}
is not possible though. How can I change my code to get rid of this warning, or do you know a better practice for my case?
The compiler complains because property
is of type Property<?>
which could or could not be of type Property<Integer>
in general. This is an inherent limitation of the current java language due to type erasure.
In this particular case you are making sure that property
is of class Property<Integer>
by use of the getType
method so it is safe to ignore the warning.
if (property.getType().equals("Integer")) {
// we have made sure property is of class Property<Integer> so the cast is type safe
@SuppressWarnings("unchecked")
Property<Integer> propInt = (Property<Integer>) property;
propInt.setValue((Integer) values[i++]);
}
It is important to document it with a comment otherwise a peer reviewing your code might not notice that indeed the cast is type safe and could confuse the warning supression as a malpractice.