java 反射 根据不同方法,不同参数动态调用方法

package com.springapp.mvc;

import java.lang.reflect.Method;

/**
* Created by baiyunpeng on 2016/8/26.
*/
public class helloWord {

/**
* @param args
*/
public static void main(String[] args) {
try {
Hello h=new Hello();
Object[] argspara=new Object[]{};
Object aa = helloWord.invokeMethod(h,"helloStrs",argspara);
System.out.println("*******"+aa.toString()+"*******");

helloWord.invokeMethod(h, "helloStrs",argspara);
argspara=new Object[]{"he"};
helloWord.invokeMethod(h, "helloStrs",argspara);
argspara=new Object[]{"she",2};
helloWord.invokeMethod(h, "helloStrs2",argspara);

} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 反射调用方法
* @param newObj 实例化的一个对象
* @param methodName 对象的方法名
* @param args 参数数组
* @return 返回值
* @throws Exception
*/
public static Object invokeMethod(Object newObj, String methodName, Object[] args)throws Exception {
Class ownerClass = newObj.getClass();
Class[] argsClass = new Class[args.length];
for (int i = 0, j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
Method method = ownerClass.getMethod(methodName, argsClass);
return method.invoke(newObj, args);
}

}

class Hello{

public String helloStrs(){
//根据不同的方法名称,调用不用的方法
System.out.println("hello1");
return "hello1";
}

public void helloStrs(String a) {
//根据不同的方法名称,调用不用的方法
System.out.println("hello11");
}

public void helloStrs2(String a ,Integer b) throws Exception{
//根据不同的方法名称,调用不用的方法
System.out.println("hello12");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值