package com.xch;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author Chenghe Xu
* @date 2022/9/21 9:42
*/
@SpringBootTest
public class Test01 {
/**
* 反射用法总结
*/
@Test
void test01() throws Exception {
//非反射创建对象
Student student1=new Student();
System.out.println(student1);
//操作对象的public属性
student1.name="xch1";
System.out.println(student1.name);
//操作对象的public方法
student1.setName("ypy1");
System.out.println(student1.getName());
//反射创建对象
//1、获取Class实例
//1.1、通过类本身.class属性获取
Class<Student> studentClass1 = Student.class;
//1.2、通过类的对象获取
Class<? extends Student> studentClass2 = student1.getClass();
//1.3、通过Class的静态方法获取
Class<?> studentClass3 = Class.forName("com.xch.Student");
//1.4、通过类加载器获取
ClassLoader classLoader = this.getClass().getClassLoader();
Class<?> studentClass4 = classLoader.loadClass("com.xch.Student");
//2、创建Class对应运行时类的对象
//2.1、默认使用无参构造函数
Student student2 = studentClass1.newInstance();
//2.2、指定使用无参构造函数
Constructor<? extends Student> studentClass2Constructor = studentClass2.getConstructor();
Student student3 = studentClass2Constructor.newInstance();
//2.3、指定使用有参构造函数
Constructor<?> studentClass3Constructor = studentClass3.getConstructor(String.class,Integer.class);
Student student4 = (Student) studentClass3Constructor.newInstance("XiaoXu", 18);
System.out.println(student2);
System.out.println(student3);
System.out.println(student4);
//操作对象的public属性
Field name = studentClass1.getField("name");
name.set(student2, "xch2");
System.out.println(name.get(student2));
//操作对象的任何修饰符属性
Field age = studentClass1.getDeclaredField("age");
age.setAccessible(true);//强制设置属性可访问
age.set(student2, 21);
System.out.println(age.get(student2));
//操作对象的public有参方法
Method setName = studentClass1.getMethod("setName", String.class);
setName.invoke(student2, "ypy2");
//操作对象的任何修饰符有参方法
Method setAge = studentClass1.getDeclaredMethod("setAge", Integer.class);
setAge.setAccessible(true);//强制设置属性可访问
setAge.invoke(student2, 20);
//操作对象的public无参方法
Method getName = studentClass1.getMethod("getName");
System.out.println(getName.invoke(student2));
//操作对象的任何修饰符无参方法
Method getAge = studentClass1.getDeclaredMethod("getAge");
getAge.setAccessible(true);//强制设置属性可访问
System.out.println(getAge.invoke(student2));
}
}
反射用法总结
于 2022-09-26 18:36:51 首次发布