简体   繁体   中英

Cast to compiletime unknown generic type

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?

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 ?.

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 .

Edit

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM