本文介绍了使用反射和泛型时出现警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何重写:
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 我会更进一步说 callMethod 根本不应该是一个通用的方法。由于调用者通过将其名称作为字符串传递来决定调用哪个方法,该方法应该返回 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.
更多推荐
使用反射和泛型时出现警告
发布评论