通过反射方式进行某个方法的调用,需要使用Method类的()方法
时间: 2024-03-22 19:38:42 浏览: 209
通过反射方式进行某个方法的调用,需要使用 Method 类的 `invoke()` 方法。该方法可以接受一个 Object 类型的参数,表示该方法所属的对象(如果该方法是静态方法,则可以传入 null)。另外,还需要传入一个参数列表,表示该方法的参数。如果该方法没有参数,可以传入一个空数组。
示例代码如下:
```java
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws Exception {
Class<?> clazz = MyClass.class;
Object obj = clazz.newInstance();
Method method = clazz.getDeclaredMethod("testMethod", int.class, String.class);
Object result = method.invoke(obj, 123, "hello");
System.out.println(result);
}
}
class MyClass {
public String testMethod(int num, String str) {
return "方法调用成功:" + num + "," + str;
}
}
```
上述代码中,我们使用反射获取了 MyClass 类中的 testMethod 方法,然后调用了该方法,并传入了两个参数。最后,将方法返回值打印出来。运行结果如下:
```
方法调用成功:123,hello
```
需要注意的是,如果被调用的方法声明了受检异常,需要在调用时处理异常。例如,在上述代码中,如果 testMethod 方法声明了 IOException 异常,那么在调用时需要使用 try-catch 语句进行处理。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)