前言
上一篇我们详细介绍了Field的用法,我们知道它是一个类用来拿到某个实体类的属性,那么Method这个类就是我们用来获取某个实体类的方法
一 方法
getMethod();
getMethods();
getDeclaredMethod();
getDeclaredMethods();
这四个方法与Field很类似,加上Declared也是只能拿本类的所有方法,不加的话只能获得本类public修饰和直接父类public修饰的方法
而不同的是:传参不同
getMethod(String methodName,Class...ParameterType);//两者都需要传方法名和方法所需要的所有参数类型
getDeclaredMethod(String methodName,Class...ParameterType);
而关于getMethods()
Method[] mes =class.getDeclaredMethods();//返回方法数组不需要传参
Method[] mes2=class.getMethods();//同理
二 使用方法
我们拿到一个目标方法,目的是使用它,那么通过反射的手法使用方法就要使用invoke()
我们拿一个学生类来举例子:用反射调用setter方法给学生对象赋值
public class Student{
private String name;
public void setName(String name){
this.name =name;
}
public String getName(){
return this.name
}
}
测试代码👇
Student stu =new Student();
Class cla =Student.class;
//setter
Method m =cla.getDeclaredMethod("setName",String.class);
m.invoke(stu,"张三");
//getter
Method m2=cla.getDeclaredMethod("getName");
String name =(String) m2.invoke(stu);//返回是Object
三 获得构造方法
关键字:Constructor<T>
public class Student{
private String name;
public Student(String name){
this.name =name;
}
}
测试代码👇
Constructor<Student> con =cla.getDeclaredConstructor(String.class);
Student stu =con.newInstance("李四");
<worning>
如果我们实体类有空参的构造方法,那么可以直接cla.newInstance(),但是,带有参数的构造方法必须通过Constructor<T>
来获得
四 总结
上一篇反射详解(一)-Field详解+今天的Method,关于反射的内容就全部说完了,纯原创,喜欢请点赞关注哦~