Method获取反射对象方法
public class Demo_Reflect {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("com.demo.Person");
Constructor c = cls.getConstructor(String.class, int.class);
Person p = (Person) c.newInstance("张三", 23);
Method m1 = cls.getMethod("run");
m1.invoke(p);// 无参方法
Method m2 = cls.getMethod("run", String.class);
m2.invoke(p, "abc");// 有参方法
}
}
class Person {
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
private String name;
private int age;
public Person(String Name, int Age) {
name = Name;
age = Age;
}
public void run() {
System.out.println("通过反射获取方法,执行成功~");
}
public void run(String Str) {
System.out.println("通过反射获取有参方法,执行成功~");
}
}
网友评论