用Java反射如何实例化一个新对象,然后调用一个方法呢? [英] With Java reflection how to instantiate a new object, then call a method on it?

查看:144
本文介绍了用Java反射如何实例化一个新对象,然后调用一个方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java很陌生,我面临一个反思问题。

I'm pretty new to Java, and I'm facing a reflection issue.

假设我必须动态调用方法类的实例上的fooMethod Foobar

Let's say i have to dynamically call the method fooMethod on an instance of the class Foobar

到目前为止我的实例是 Foobar with:

I got so far an instance of Foobar with:

Object instance = Class.forName("Foobar").newInstance();

假设我知道有一种方法 fooMethod 在这个对象上(我甚至可以用 Class.forName(Foobar)。getDeclaredMethods())查看,请问如何调用它?

Let's say I know there's a method fooMethod on this object (I can even check this with Class.forName("Foobar").getDeclaredMethods() ) , how to call it, please?

推荐答案

Method method = getClass().getDeclaredMethod("methodName");
m.invoke(obj);

这是方法没有参数的情况。如果有,则将参数类型作为参数附加到此方法。
obj 是您调用方法的对象。

This is in case the method doesn't have arguments. If it has, append the argument types as arguments to this method. obj is the object you are calling the method on.

查看java.lang.Class文档

这篇关于用Java反射如何实例化一个新对象,然后调用一个方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆