Reputation: 28
So, I got a problem with casting to an unknown (at runtime) generic method argument.
ValueDescription<?> valueDesc = /* get the value description */;
Object value = /* get the value */;
valueDesc.gotAValue(valueDesc.getType().cast(value));
The abstract class ValueDescription looks like this:
public abstract class ValueDescription<T> {
public abstract Class<T> getType();
public void gotAValue(final T value) {
// do something
}
}
Eclipse allways gives the following error:
The method gotAValue(capture#1-of ?) in the type ValueDescription is not applicable for the arguments (capture#2-of ?)
Is it even possible to do something like this?
Upvotes: 1
Views: 926
Reputation: 8363
If you are not supposed to know the actual generic type of ValueDescription
, then you should let the class do it for you.
public abstract class ValueDescription<T> {
public abstract Class<T> getType();
public void gotAValue(final Object value) {
final T castedValue = getType().cast(value);
// Continue
}
}
If you do this, you may need to throw an appropriate exception if the Object
type value
cannot be casted to the actual type.
If it is possible to determine the type of valueDesc
, then use Andy's solution.
Actually, if you do not know the type of ValueDescription
, then it is likely that this class does not need to have generic at all. getType()
can simply return a Class<?>
and subclass just needs to override it to return the correct Class
object.
Upvotes: 1
Reputation: 140309
Put this code into a generic method:
<T> void doStuff(ValueDescription<T> valueDesc) {
Object value = /* get the value */;
valueDesc.gotAValue(valueDesc.getType().cast(value));
}
This allows the compiler to know that the getType()
and gotAValue
"?
s" are the same type, even when you don't know the T
directly:
ValueDescription<?> valueDesc = /* get the value description */;
doStuff(valueDesc); // Fine, even though you've only got ?.
Upvotes: 1