前情回顾:java中用反射创建类对象,操作属性
反射操作方法
1.获取方法:
* getMethods() // 获取所有的公共方法包括父类
* getDeclaredMethods() // 获取所有声明的方法不包括父类
* getMethod(String name,Class...cla) // 获取指定的公共方法
String name ———————— 表示方法名
Class...cla ————————表示方法接收的参数类型的**类对象**
* getDeclaredMethod(String name,Class...cla) //获取指定的声明方法
String name ———————— 表示方法名
Class...cla ———————— 表示方法接收的参数类型的类对象
2.操作方法
* 静态方法: 方法对象.invoke(null,参数值1,参数值2,....);//参数类型
* 方法对象.invoke(null,null);
* 非静态方法:Object obj=cla.newInstance();
方法对象.invoke(obj,参数值1,参数值2,....)
方法对象.invoke(obj,null)
2.代码:
//操作方法
private static void operMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//获取类对象
Class cla=Class.forName("com.bjsxt.pojo.Student");
//获取类方法对象
//获取所有的公共方法包括父类
Method[] ms=cla.getMethods();
for(Method m:ms){
System.out.println("获取方法名--->"+m.getName());
}
System.out.println("************************************");
//获取所有声明的方法不包括父类
Method[] ms2=cla.getDeclaredMethods();
for(Method m:ms2){
System.out.println("获取方法名--->"+m.getName());
}
//获取指定的公共方法包括父类
Method m=cla.getMethod("pHi", int.class,String.class);
System.out.println(m.getReturnType());
//获取指定的声明的方法,不包括父类
Method m2=cla.getDeclaredMethod("sHello",null);
System.out.println(m2.getName());
//执行方法
//静态方法
Method m3=cla.getDeclaredMethod("sHi",String.class);
m3.invoke(null, "String参数");
//非静态
Method m4=cla.getDeclaredMethod("sHi",int.class,String.class);
m4.invoke(cla.newInstance(), 3,"String参数");
}