获取class对象
@Testvoid reflect() throws Exception {Class userClass = User.class;System.out.println(userClass.getName()); // 全类名 com.zyw.proxydemo.pojo.UserSystem.out.println(userClass.getSimpleName()); // 简名 UserClass userClass1 = Class.forName("com.zyw.proxydemo.pojo.User");System.out.println(userClass == userClass1);User user = new User();Class userClass2 = user.getClass();System.out.println(userClass1 == userClass2);}
输出结果
User在内存中只存在一份class对象,所有三种方式拿到的是同一个class对象
获取类的构造器
@Testvoid reflect() throws Exception {Class userClass = User.class;Constructor[] constructors = userClass.getConstructors();for (Constructor constructor : constructors) {System.out.println(constructor.getName() + "--->" + constructor.getParameterCount());}// 获取某个构造器// 有参构造 public User(String name, Integer age) Constructor constructor = userClass.getConstructor(String.class, Integer.class);// 无参构造Constructor constructor1 = userClass.getConstructor();}
用构造器创建对象
@Testvoid reflect() throws Exception {Class userClass = User.class;// 获取某个构造器// 有参构造 public User(String name, Integer age)Constructor constructor = userClass.getDeclaredConstructor(String.class, Integer.class);// 无参构造Constructor constructor1 = userClass.getDeclaredConstructor();User user = (User) constructor1.newInstance();user.setName("chenlin");user.setAge(18);constructor.setAccessible(true); // 禁止检查访问权限 User user1 = (User) constructor.newInstance("mahong", 18);System.out.println(user1.getName());}
获取类的成员变量
@Testvoid reflect() throws Exception {Class userClass = User.class;Field[] fields = userClass.getDeclaredFields();for (Field field : fields) {System.out.println(field.getName() + ": " + field.getType());}// 某个成员变量Field age = userClass.getDeclaredField("age");age.setAccessible(true); // 暴力反射// 赋值User user = new User();age.set(user, 18);// 取值Integer age1 = (Integer) age.get(user);System.out.println(age1);}
获取类的成员方法
@Testvoid reflect() throws Exception {Class userClass = User.class;// 获取所有的方法Method[] methods = userClass.getDeclaredMethods();// 获取某个方法Method method = userClass.getDeclaredMethod("say", String.class);method.setAccessible(true);User user = new User();String result = (String) method.invoke(user, "nihao");System.out.println(result);}
应用场景
- 反射在框架开发中广泛使用, 下面是一个简单使用的例子
import java.io.*;
import java.lang.reflect.Field;/*** 将对象信息持久化到文件* @author zhou yu* @date 2024/4/9 8:29*/
public class ObjectFrame {public static void savaObject(Object object) throws Exception {Class oClass = object.getClass();String simpleName = oClass.getSimpleName();BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src\\save.txt", true)));bw.write("-------------" + simpleName + "-------------\n");Field[] fields = oClass.getDeclaredFields();for (Field field : fields) {field.setAccessible(true);String name = field.getName();String value = field.get(object) + "";bw.write(name + ": " + value + "\n");}bw.write("\n");bw.flush();bw.close();}
}