Java反射;如何使用 Method.invoke() 检索对象数组?
我需要一些在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需将 Method.invoke() 的返回值转换为您碰巧知道的任何值。不是很稳健,但这就是反思的风险!所以在这种情况下,它将是:
顺便说一句,请注意,如果该方法返回一个原语(
int
、double
等),Method.invoke
将返回其盒装等效项(Integer
、Double
等)。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:
Btw, note that if the method returns a primitive (
int
,double
, etc),Method.invoke
will return its boxed equivalent (Integer
,Double
, etc).Object[]
是一个对象 - 将invoke
的结果转换为Object[]
。An
Object[]
is an object--cast the result ofinvoke
toObject[]
.