package text;
import java.lang.reflect.Method;
public class ReflectDemo4 {
public static void main(String[] args) throws Exception {
getMethodDemo();
}
/*
* 获取指定Class中所有的公共函数
* */
public static void getMethodDemo() throws Exception{
Class clazz=Class.forName("text.Person");
//getMethods()返回一个方法数组
Method[] methods= clazz.getMethods(); //获取的都是公有的方法(包含父类的方法),没有获取到Person类私有方法method()
// methods=clazz.getDeclaredMethods(); //只获取本类中所有方法,包含私有
for(Method method:methods){
System.out.println(method);
}
}
}
运行结果:
可以看到,方法中也出现了父类的方法,并且所有的方法都是公有的。那么如何获取类中的私有方法呢?
package text;
import java.lang.reflect.Method;
public class ReflectDemo4 {
public static void main(String[] args) throws Exception {
getMethodDemo();
}
/*
* 获取指定Class中所有的公共函数
* */
public static void getMethodDemo() throws Exception{
Class clazz=Class.forName("text.Person");
//getMethods()返回一个方法数组
Method[] methods= clazz.getMethods(); //获取的都是公有的方法(包含父类的方法),没有获取到Person类私有方法method()
methods=clazz.getDeclaredMethods(); //只获取本类中所有方法,包含私有
for(Method method:methods){
System.out.println(method);
}
}
}
运行结果:
上例演示了获取Class中的所有方法,下面演示获取一个方法:
package text;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectDemo4 {
public static void main(String[] args) throws Exception {
getMethodDemo_2();
}
public static void getMethodDemo_2() throws Exception{
Class clazz=Class.forName("text.Person");
Method method= clazz.getMethod("show",null); //获取空参数的show()方法
// Object obj=clazz.newInstance(); //创建一个对象来运行show()方法(无参的构造方法)
//使用有参的构造方法来创建对象
Constructor constructor =clazz.getConstructor(int.class,String.class);
Object obj=constructor.newInstance(37,"小明");
method.invoke(obj, null);
}
}
运行结果:
在这里我们演示的是获取没有参数的方法,接下来我们再演示获取有参数的方法:
package text;
import java.lang.reflect.Method;
public class ReflectDemo4 {
public static void main(String[] args) throws Exception {
getMethodDemo_3();
}
public static void getMethodDemo_3() throws Exception{
Class clazz=Class.forName("text.Person");
Method method= clazz.getMethod("paramMethod",String.class,int.class); //获取参数列表为String,int的paramMethod方法
Object obj=clazz.newInstance(); //创建一个对象来运行paramMethod方法
method.invoke(obj, "小强",89);
}
}
运行结果: