反射获取方法
Method
Class.getMethod(String, Class...) 和 Class.getDeclaredMethod(String, Class...)方法可以获取类中的指定方法,调用invoke(Object, Object...)可以调用该方法,Class.getMethod("eat") invoke(obj) Class.getMethod("eat",int.class) invoke(obj,10)
public class Demo_Method { /** * Class.getMethod(String, Class...) 和 Class.getDeclaredMethod(String, * Class...)方法可以获取类中的指定方法,调用invoke(Object, * Object...)可以调用该方法,Class.getMethod("eat") invoke(obj) * Class.getMethod("eat",int.class) invoke(obj,10) * @throws Exception */ public static void main(String[] args) throws Exception { Class clazz = Class.forName("com.loaderman.bean.Person"); Constructor c = clazz.getConstructor(String.class,int.class);//获取有参构造 Person p = (Person) c.newInstance("张三",23); //通过有参构造创建对象 Method m = clazz.getMethod("eat"); //获取eat方法 m.invoke(p); Method m2 = clazz.getMethod("eat", int.class); //获取有参的eat方法 m2.invoke(p, 10); } }
package com.loaderman.bean; public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) //判断调用对象和传入对象的字节码文件是否是同一个字节码文件 return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public void eat() { System.out.println("今天吃了一顿金钱豹"); } public void eat(int num) { System.out.println("今天吃了" + num + "顿金钱豹"); } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!