版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82730163
/**
* 字节码对象获取一个类里面所有的方法
* @author 郑清
*/
public class Demo {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
test();
}
public static void test() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
//获取类的字节码对象
Class cla = Student.class;
//获取无参公共(public)的构造方法
Constructor constructor = cla.getConstructor();
Object newInstance = constructor.newInstance();
//获取Student类里面所有公共(public)的方法(包括默认继承父类Object里面的所有公共(public)的方法)
Method[] methods = cla.getMethods();
for (Method method : methods) {
System.out.println(method);
}
//表示得到了一个方法,而且是cla所表示的类中的方法,对象方法
Method method = cla.getMethod("add", String.class);
method.invoke(newInstance, "1");
}
}
class Student {
public Student() {}
public Student(String name) {}
public Student(String name, int age) {}
private Student(int age) {}
public void add() {}
public void add(String name) {
System.out.println("这是add方法...");
}
private void add(String name,int age) {}
}
运行结果图: