import java.lang.reflect.Method;
class A {
public void print() {
System.out.println("helloworld");
}
public void print(int a, int b) {
System.out.println(a + b);
}
public void print(String a, String b) {
System.out.println(a.toUpperCase() + "," + b.toLowerCase());
}
}
public class MethodDemo1 {
public static void main(String[] args) {
// 获取方法名称和参数列表来决定
// getMethod获取的是public的方法
// getDelcaredMethod自己声明的方法
A a1 = new A();
Class c = a1.getClass();
try {
// 1.获取方法print(int,int)
// Method m = c.getMethod("print", new Class[]{int.class,int.class});
Method m = c.getMethod("print", int.class, int.class);
// 方法的反射操作是用m对象来进行方法调用 和a1.print调用的效果完全相同
// Object o = m.invoke(a1,new Object[]{10,20});
Object o = m.invoke(a1, 10, 20);
System.out.println("==================");
// 2.获取方法print(String,String)
Method m1 = c.getMethod("print", String.class, String.class);
o = m1.invoke(a1, "hello", "WORLD");
System.out.println("===================");
// 3.获取方法print()
// Method m2 = c.getMethod("print", new Class[]{});
Method m2 = c.getMethod("print");
// m2.invoke(a1, new Object[]{});
m2.invoke(a1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 输出
30
==================
HELLO,world
===================
helloworld