使用反射和泛型时出现警告

编程入门 行业动态 更新时间:2024-10-21 14:31:59
本文介绍了使用反射和泛型时出现警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何重写:

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.

更多推荐

使用反射和泛型时出现警告

本文发布于:2023-11-16 23:59:33,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   泛型时

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!