Java反射;如何使用 Method.invoke() 检索对象数组?

发布于 2024-12-19 18:57:32 字数 114 浏览 1 评论 0原文

我需要一些在 Java 中使用反射的帮助。我需要使用反射来调用返回对象数组的方法。 Method.invoke() 仅返回一个对象。这是怎么做到的?

非常感谢您的任何见解!

I need some help using reflection in Java. I need to use reflection to call a method that returns an Object array. Method.invoke() only returns an Object. How is this done?

Many thanks for any insights!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明媚如初 2024-12-26 18:57:32

您只需将 Method.invoke() 的返回值转换为您碰巧知道的任何值。不是很稳健,但这就是反思的风险!所以在这种情况下,它将是:

Object[] result = (Object[]) method.invoke(...);

顺便说一句,请注意,如果该方法返回一个原语(intdouble等),Method.invoke 将返回其盒装等效项(IntegerDouble 等)。

You just have to cast the return value of Method.invoke() to whatever you happen to know it is. Not very robust, but such are the risks of reflection! So in this case, it would be:

Object[] result = (Object[]) method.invoke(...);

Btw, note that if the method returns a primitive (int, double, etc), Method.invoke will return its boxed equivalent (Integer, Double, etc).

泡沫很甜 2024-12-26 18:57:32

Object[] 是一个对象 - 将 invoke 的结果转换为 Object[]

An Object[] is an object--cast the result of invoke to Object[].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文