使用反射和泛型时出现警告 [英] Warning while using reflection and generics
本文介绍了使用反射和泛型时出现警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何重写:
How do I rewrite this:
<T> T callMethod(String methodName, Object[] parameters) throws ... {
...
return (T) SomeClass.class.getDeclaredMethod(methodName, parameterTypes).invoke(binding, parameters);
}
所以不会产生警告
warning: [unchecked] unchecked cast
return (T) SomeClass.class.getDeclaredMethod(methodName, parameterTypes).invoke(binding, parameters);
required: T
found: Object
where T is a type-variable:
T extends Object declared in method <T>callMethod(String,Object[])
我的意思是没有SupressWarnings解决方案。
I mean the no-SupressWarnings solution.
推荐答案
正如Peter Lawrey 指出:
As Peter Lawrey pointed out:
编译器无法在编译时确定您在运行时选择的
方法的返回类型为T
我会更进一步说 Object
- 比如 invoke
- 强制调用网站投射。
I'll go a step further and say that callMethod
should not be a generic method at all. Since the caller decides what method is called by passing its name as a string, the method should just return Object
- like invoke
- and force the call site to cast.
不要使用 @SuppressWarnings
- 没有办法证明它的正确性这里。
Do not use @SuppressWarnings
- there's no way to justify it here.
这篇关于使用反射和泛型时出现警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文