我有一些对象,它们预先生成一些配置,以便之后能更快地处理计算(可能多次)。我正在尝试通用化它,以避免每次传递配置时都将其作为 Object
并进行转换。
interface IComputable<T> {
T configure(); // Generate configuration object
int compute(T conf); // Run the computation based on the pre-generated configuration
float precision(T conf); // Make the compute() computation finer-grained
...
}
class ComputableInfo {
IComputable<?> computable;
Object config; // Real type is <?>
int result;
ComputableInfo(String id) {
computable = ComputableFactory.createFrom(id);
config = computable.configure();
result = computable.compute(config); // <<<--- The method compute(capture#3-of ?) in the type TestInterface.IComputable<capture#3-of ?> is not applicable for the arguments (Object)
}
}
我得到一个编译错误:
在TestInterface.IComputable<capture#3-of ?>类型中,方法compute(capture#3-of ?)对于参数(Object)不适用
当然,我可以将 int compute(T conf)
替换为 int compute(Object conf)
但是我需要显式地将其强制转换为适当的 T
。这并不是很大的问题,但会使代码不够明显。
我也可以让 ComputableInfo
成为泛型:
interface ComputableInfo<T> {
IComputable<T> computable;
T config;
...
但是这样会在其他一些地方(主要是“原始类型”警告)引起编译问题,我希望避免比之前的解决方法更多的问题(使用T
的替代方法是使用Object
)。
有没有办法实现这一点?我甚至愿意将这种问题从错误转变为编译器设置中的警告,或者也许有一个额外的私有方法,可以返回包含config
和result
的单个对象?
编辑:关于如果我使ComputableInfo
成为泛型的“进一步编译问题”,我在接口中有另一个方法(请参见编辑后的内容),该方法通过ComputableInfo
调用:
ComputableInfo<?> info = getInfo(id);
info.computable.precision(info.config); // <<<--- (same kind of error)
问题在于
ComputableInfo
无法知道Computable<T>
的类型T
(至少我不知道如何知道),因为它来自一个从配置文件构建的工厂。
ComputableInfo
类型变成泛型类型是正确的解决方案。修复其他警告即可。 - chrylis -cautiouslyoptimistic-IComputable<?>
是一个持有某些未知类型的IComputable
,你不能传递任意的Object
给它,因为编译器无法检查该对象是否为正确的类型。这与你不能向List<?>
添加元素的原因相同,在 SO 上已经被问答过很多次了。你可以将你的IComputable<?>
强制转换为IComputable<Object>
,但这是一种丑陋和不安全的类型操作。 - JesperIComputable<? super Object> computable;
这个怎么样? - Nikolas Charalambidis