通过Method对象执行方法
【方法】
Object invoke(Object obj,Object... parameters)
;【重中之重】
class Panda{
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//创建Class类对象
Class test = Test.class;
//获取Method对象 test() 成员方法 没有参数
Method method = test.getMethod("test");
//创建Constructor对象 获取指定参数类型的构造方法
Constructor con = test.getConstructor();
//通过创建的Constructor对象【获取类对象】等与new 对象
Test test1 = (Test) con.newInstance();
//调用invoke() 方法通过Method对象执行方法
//【参数需要操作类的类对象】而且这个类对象是属于这个类的,不是Class类
Object ob = method.invoke(test1);
}
}
@Data
public class Test{
//成员变量
private String name;
private Integer age;
private String sex;
//无参构造方法
public Test(){}
//有参构造方法
public Test(String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
private Test(String name, Integer age){
this.name = name;
this.age = age;
}
//公有成员方法
public String test(){
return "小哈";
}
//公有成员方法
public String test(String name,Integer age){
return name+age;
}
//私有成员方法【重载】
private String test(String message){
return message;
}
}