反射 三 反射method

/**
* 总结:与获取构造函数的方式类似
*这里用clazz.getMethod(方法名,方法的参数的类型的字节码),来获取方法
*然后通过得到的method.invoke(对象,传进参数值)来调用method
*/
//public void xx1()
@Test
public void test1() throws Exception{

Person p = new Person();
p.xx1();

Class clazz = Class.forName

("cn.itcast.reflect.Person");
Method method = clazz.getMethod("xx1", null);
method.invoke(p, null);

}

@Test
public void test2() throws Exception,

InstantiationException, IllegalAccessException{
String className = "cn.itcast.reflect.Person";
String methodName = "xx1";

Object obj = Class.forName(className).newInstance();
Method m = Class.forName(className).getMethod

(methodName, null);
m.invoke(obj, null);
}


//public String xx1(String name, int arr[])
@Test
public void test3() throws Exception{

Person p = new Person();
Class clazz = Class.forName

("cn.itcast.reflect.Person");
Method method = clazz.getMethod("xx1",

String.class,int[].class);
String returnValue = (String) method.invoke(p,

"aaa",null);
System.out.println(returnValue);
}

//private int[] xx1(List list)
@Test
public void test4() throws Exception{

Person p = new Person();
Class clazz = Class.forName

("cn.itcast.reflect.Person");
Method method = clazz.getDeclaredMethod("xx1",

List.class);
method.setAccessible(true);
int[] arr = (int[]) method.invoke(p, new ArrayList

());
System.out.println(arr);
}

//public static void xx1(Map map)
@Test
public void test5() throws Exception{

Class clazz = Class.forName

("cn.itcast.reflect.Person");
Method method = clazz.getDeclaredMethod("xx1",

Map.class);
method.invoke(null, new HashMap());

}

//public static void main(String[] args)
@Test
public void test6() throws Exception{

Class clazz = Class.forName

("cn.itcast.reflect.Person");
Method method = clazz.getMethod("main",String

[].class);
//method.invoke(null, new Object[]{new String[]

{"1","2"}});
method.invoke(null, (Object)new String[]{"1","2"});
//Method public Object invoke(Object obj,Object...

args) 1.5
//Method public Object invoke(Object obj,Object[]

args) 1.4 main(String s1,String s2)

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值