I’ve got a generic class with subclass.
public class GenericClass<C>
{
private C value;
public C getValue() { return value; }
public void setValue(C value) { this.value = value; }
}
In my code I use subclasses without knowing what subclasses but I know this two subclasses are same type :
GenericClass<?> obj1 = ... // has a value here
GenericClass<?> obj2 = ... // has a value here
// I know that obj1 is the same type of obj2 but I don't know this type.
obj1.setValue(obj2.getValue());
The last line produce a compilation error which is :
The method setValue(capture#11-of ?) in the type GenericClass is
not applicable for the arguments (capture#12-of ?)
How can I do that (something like casting a wildcard…) ?
Since
GenericClass<?>holds no information of the actual enclosed type, the compiler has no way to ensure that two such classes are compatible. You should use a concrete named generic type parameter. If you don’t know the concrete type, you may still be able to enforce the sameness of the two type parameters by e.g. enclosing the above code in a generic method:If this is not possible, you may as a last resort try explicit casts, or using raw types. This will trade the compilation error to unchecked cast warning(s).