反射获取成员方法method()-其他
反射获取成员方法method()
public class MethodDemo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException {
// 获取Class对象
Class clazz = Class.forName("reflect.Student");
// 获取公共的成员方法,包括父类继承的方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
// 获取所有成员方法,不包括继承的
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
// 获取单个公共的成员方法getMethod(String name, Class<?>... parameterTypes)
// 参数1是方法名,参数2是方法的参数,方法没有参数可以不写
Method method = clazz.getMethod("show");
System.out.println(method);
// 获取一个有形参的方法
Method method1 = clazz.getMethod("show1", String.class);
System.out.println(method1);
// 获取单个成员方法
Method method2 = clazz.getDeclaredMethod("test");
System.out.println(method2);
}
}
public class Student {
public String name;
public int age;
private int money = 100;
public void show() {
System.out.println("公共方法");
}
public void show1(String name) {
System.out.println("公共有参方法");
}
private void test() {
System.out.println("私有方法:");
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", money=" + money + "]";
}
}
————————
public class MethodDemo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException {
// 获取Class对象
Class clazz = Class.forName("reflect.Student");
// 获取公共的成员方法,包括父类继承的方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
// 获取所有成员方法,不包括继承的
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
// 获取单个公共的成员方法getMethod(String name, Class<?>... parameterTypes)
// 参数1是方法名,参数2是方法的参数,方法没有参数可以不写
Method method = clazz.getMethod("show");
System.out.println(method);
// 获取一个有形参的方法
Method method1 = clazz.getMethod("show1", String.class);
System.out.println(method1);
// 获取单个成员方法
Method method2 = clazz.getDeclaredMethod("test");
System.out.println(method2);
}
}
public class Student {
public String name;
public int age;
private int money = 100;
public void show() {
System.out.println("公共方法");
}
public void show1(String name) {
System.out.println("公共有参方法");
}
private void test() {
System.out.println("私有方法:");
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", money=" + money + "]";
}
}