【Java】【反射】Method获取反射对象方法

2017-04-08  本文已影响80人  JerichoPH

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("通过反射获取有参方法,执行成功~");
    }
}
上一篇下一篇

猜你喜欢

热点阅读