反射 三 反射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)

}

你可能感兴趣的:(method)