Java反射中的Method类表示一个类的方法,可以通过Method类的实例来调用该方法。Method类提供了许多方法,可以获取方法的名称、返回值类型、参数类型等信息,还可以通过invoke方法动态调用方法。
示例:
一、自定义一个Person类,其中有两个方法
class Person {
public void sayHello(String name) {
System.out.println("Hello, " + name);
}
private void privateMethod() {
System.out.println("This is a private method.");
}
}
二、在main方法中实现步骤
1.首先获取Person类的Class对象
Class<?> clazz = Person.class;
2.获取所有声明的方法(不包括从父类继承的方法)
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod.getName());
}
3.获取指定方法:该部分代码通过调用Class类的getMethod方法获取指定方法,并打印方法名。
Method method = clazz.getMethod("sayHello", String.class);
System.out.println(method.getName());
4.调用方法:该部分代码通过调用Method类的invoke方法动态调用方法,并传入方法的参数。
Person person = new Person();
method.invoke(person, "Tom");
整体代码
import java.lang.reflect.Method;
public class MethodExample {
public static void main(String[] args) throws Exception {
// 获取Person类的Class对象
Class<?> clazz = Person.class;
// 获取所有公共方法(包括从父类继承的方法)
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
// 获取所有声明的方法(不包括从父类继承的方法)
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod.getName());
}
// 获取指定方法
Method method = clazz.getMethod("sayHello", String.class);
System.out.println(method.getName());
// 调用方法
Person person = new Person();
method.invoke(person, "Tom");
}
}
运行结果
sayHello
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
sayHello
privateMethod
sayHello
Hello, Tom