我的程序存储映射到接受此类参数的操作的参数类型。 当使用显式类型检索存储的操作时,使用给定类型的对象作为参数调用操作的方法是没有问题的。 但是,当使用仅隐式已知的类型时,调用操作的方法会导致错误:
public class StoredArgumentTypeProblem {
static class Operation<T> {
T apply(T arg) {
return arg;
}
}
static class OperationContainer {
private Map<Class<?>, Operation<?>> storedOperations = new HashMap<>();
public <T> void put(Class<T> argType, Operation<T> opp) {
storedOperations.put(argType, opp);
}
public Class<?> getSomeStoredKey() {
return storedOperations.keySet().iterator().next();
}
public <T> Operation<T> get(Class<T> type) {
// unchecked cast, but should work given restrictions on put.
return (Operation<T>)storedOperations.get(type);
}
}
public void test() {
OperationContainer container = new OperationContainer();
container.put(Integer.class, new Operation<Integer>());
container.get(Integer.class).apply(new Integer(1234));
Class<?> keyType = container.getSomeStoredKey();
// ERROR: method apply in Operation<T> cannot be applied to given types
container.get(keyType).apply(keyType.cast(new Integer(5678)));
}
}
当然,从Java的角度来看,这个错误是完全合理的;捕获“?”的 #1与捕获“?”的 #2 无关。但我们人类可以看到,在这种情况下,使用 keyType 强制转换的参数调用“apply(…)”是可行的。
是否有可能“欺骗”Java并以某种方式动态应用存储的操作?
使用某种类型的类型转换?使用注释?还有其他想法吗? ...
最佳答案
此问题与通配符捕获的限制有关。通配符本质上就像独立的类型参数一样工作,并且无法表达它们之间的关系。作为解决方法,您可以使用“捕获助手”方法,该方法使用实际类型参数来表达该关系:
private <T> void apply(
OperationContainer container,
Class<T> keyType,
Object argument
) {
T castArgument = keyType.cast(argument);
Operation<T> operation = container.get(keyType);
operation.apply(castArgument);
}
public void test() {
OperationContainer container = new OperationContainer();
container.put(Integer.class, new Operation<Integer>());
container.get(Integer.class).apply(new Integer(1234));
Class<?> keyType = container.getSomeStoredKey();
apply(container, keyType, new Integer(5678));
}
关于java - 如何使用运行时类型信息调用泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17301179/