反射的定义:
反射获取类对象的三种方式:
1.类型.class
2.Class.forName(“类型的全路径名”)
3.对象.getClass( )
public class Student {
public int stuId;
private String name;
String gender;
private Student() {
}
private Student(int stuId, String name, String gender) {
this.stuId = stuId;
this.name = name;
this.gender = gender;
}
private int getStuId() {
return stuId;
}
private void setStuId(int stuId) {
this.stuId = stuId;
}
private String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
private String getGender() {
return gender;
}
private void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
public class testStudent<T> {
public static void main(String[] args) throws Exception {
/*testStudent s=new testStudent();
//获取类对象的另一种方法
Class<? extends testStudent> aClass = s.getClass();*/
//1.获取类对象
// Class<Student> stu = Student.class;
Class<?> stu = Class.forName("Student");
//2.通过类对象获取构造方法
Constructor<Student> con= (Constructor<Student>) stu.getDeclaredConstructor();
con.setAccessible(true);//获取父类文件
//3.通过构造方法创建对象
Student student=con.newInstance();
student.stuId=1;
student.gender="男";
student.setName("王");
System.out.println(student);
}
反射常用类
通过Field类获取属性,并赋值
public static void main(String[] args) throws Exception {
Student s=testStudent.getStudent();
Class c=Student.class;
Field stuId = c.getField("stuId");
stuId.set(s,11);
System.out.println(s);
Field name=c.getDeclaredField("name");
name.setAccessible(true);//获取权限
name.set(s,"老夫子");
System.out.println(s);
Field[] f=c.getDeclaredFields();
for (Field field : f) {
field.setAccessible(true);
System.out.println(field.get(s));
}
}
通过Constructor类获取构造方法
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<Student> c = Student.class;
Constructor<Student> sClass =
c.getDeclaredConstructor(int.class,String.class,String.class);
sClass.setAccessible(true);
Student s=sClass.newInstance(2,"马","马");
System.out.println(s);
}
通过Method类获取getStuId()方法
public static void main(String[] args) throws Exception {
Student s = testStudent.getStudent();
Class<Student> c=Student.class;
Method setStuId = c.getDeclaredMethod("setStuId", int.class);
setStuId.setAccessible(true);
setStuId.invoke(s,3);
Method getStuId=c.getDeclaredMethod("getStuId");
getStuId.setAccessible(true);
Object stuId= getStuId.invoke(s);
System.out.println(s);
}
反射机制的优缺点:
可以越权,程序进行时注入数据
代码繁琐,不安全