wildcard, generic, setter and getter in java
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.开发者_JAVA百科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:
public <T> void someMethod() {
GenericClass<T> obj1 = ... // has a value here
GenericClass<T> obj2 = ... // has a value here
obj1.setValue(obj2.getValue());
}
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).
You need to type your method:
public static <T extends GenericClass<?>> void someMethod() {
T obj1 = ... // has a value here
T obj2 = ... // has a value here
// Now they are the same type
obj1.setValue(obj2.getValue());
}
Try that. Let me know if it doesn't compile (and supply the code)
精彩评论