反射
1.获取类的字节码文件对象
- Object类的getClass方法:通过类对象获取类的字节码文件对象
Student s = new Student();
Class clazz = s.getClass();
- 类的class属性:通过类名.class获取类的字节码文件对象
Class clazz = Student.class;
- Class类的forName方法:通过类的全限定名称获取类的字节码文件对象
Class clazz = Class.forName("com.qf.Test_01.Student");
2.通过反射访问类的成员属性
public class Student {
public String name;
private int age;
String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
private Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
public void show() {
System.out.println("love 57");
}
private void method(String name) {
System.out.println("marry with "+name);
}
}
Class clazz = Class.forName("com.qf.Test_01.Student");
Object obj = clazz.newInstance();
Field nameField = clazz.getField("name");
Field ageField = clazz.getDeclaredField("age");
Field genderField = clazz.getDeclaredField("gender");
nameField.set(obj,"高圆圆");
ageField.setAccessible(true);
ageField.set(obj,42);
genderField.set(obj,"女");
System.out.println(obj);
Field[] fields = clazz.getFields() ;
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
3.通过反射获取类的构造器并成员属性赋值
Class clazz = Class.forName("com.qf.Test_01.Student");
Constructor constructor = clazz.getConstructor(String.class,int.class,String.class);
Object obj = constructor.newInstance("高圆圆",42,"女");
Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
Object obj2 = declaredConstructor.newInstance("赵又廷", 45);
System.out.println(obj2);
Constructor[] constructors = clazz.getConstructors();
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor constructor1 : constructors) {
System.out.println(constructor1);
}
for (Constructor declaredConstructor1 : declaredConstructors) {
System.out.println(declaredConstructor1);
}
System.out.println(obj);
4.通过反射访问类的成员方法
Class clazz = Class.forName("com.qf.Test_01.Student");
Object obj = clazz.newInstance();
Method show = clazz.getMethod("show");
show.invoke(obj);
Method method = clazz.getDeclaredMethod("method", String.class);
method.setAccessible(true);
method.invoke(obj, "57");
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod);
}
|