- import java.lang.reflect.Method;
- public class InvokeTester {
- public int add(int param1, int param2) {
- return param1 + param2;
- }
- public String echo(String mesg) {
- return "echo " + mesg;
- }
- public static void main(String[] args) throws Exception {
- Class classType = InvokeTester.class;
- Object invokertester = classType.newInstance();
- Method addMethod = classType.getMethod("add", new Class[] { int.class,
- int.class });
- //Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,
- //如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,
- //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,
- //再将其返回
- Object result = addMethod.invoke(invokertester, new Object[] {
- new Integer(100), new Integer(200) });
- //在jdk5.0中有了装箱 拆箱机制 new Integer(100)可以用100来代替,系统会自动在int 和integer之间转换
- System.out.println(result);
- Method echoMethod = classType.getMethod("echo",
- new Class[] { String.class });
- result = echoMethod.invoke(invokertester, new Object[] { "hello" });
- System.out.println(result);
- }
- }
一个例子弄懂invoke方法
最新推荐文章于 2025-10-13 08:48:26 发布
本文通过Java反射API的实例演示了如何获取类、方法和字段,并展示了如何使用反射进行方法调用,包括传入基本类型参数的转换与处理。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Stable-Diffusion-3.5
图片生成
Stable-Diffusion
Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率
1980





