反射调用参数为数组的方法2019-02-152019-02-15
2019-02-15 本文已影响0人
我以前是学渣
反射类
public static Boolean callMethod(String json,Map map) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String id_card = "蛇精病";
String pop_other = "小妖精";
String[] s = new String[2];
s[0]=id_card;
s[1]=pop_other;
//根据全类名获取一个class对象
Class<?> clz = Class.forName("com.gsww.dgms.rule.batch.utils.CallMethodUtil");
//获取类对象
Constructor<?> declaredConstructor = clz.getDeclaredConstructor();
//创建此class所表示的类的实例对象
Object obj = declaredConstructor.newInstance();
// 获取一个形式参数为String[]的方法
Method method = obj.getClass().getDeclaredMethod(methodName,new Class[]{String[].class});
//开启强制访问
method.setAccessible(true);
// 调用方法
return (Boolean) method.invoke(obj, (Object) s);
}
目标类
public class CallMethodUtil {
private void show(String[] strings){
System.out.println("执行show方法完毕,ok"+strings[0]+"---"+strings[1]);
}
}
执行结果
![](https://img.haomeiwen.com/i4630111/108dce9bb4fd069d.png)