✨大家好,我是【zhuzicc】~ ,一位主攻【Java】的 攻城狮!✨


文章目录

  • 设置/获取属性
  • 方式一
  • 方式二
  • 方式三
  • 场景案例



本文总结:Java 通过反射设置对象属性值,或者获取对象属性值,编码过程中反射结合泛型使用可以代码复用,减少冗余代码;


食用建议:配合场景案例食用更佳;

设置/获取属性

实体类对象:

@AllArgsConstructor
@NoArgsConstructor
@Data
public class StudentScore {
    /**
     * 名称
     */
    private String name;
    /**
     * 科目
     */
    private String subject;
    /**
     * 成绩
     */
    private Integer score;
}

方式一

通过Field操作属性:

public void method1() throws Exception {
        Class<StudentScore> cls = StudentScore.class;
        StudentScore obj = new StudentScore();
        StudentScore obj2 = new StudentScore();
        /*
         * 设置属性
         */
        Field nameField = cls.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(obj, "张三");

        Field subjectField = cls.getDeclaredField("subject");
        subjectField.setAccessible(true);
        subjectField.set(obj, "语文");

        Field scoreField = cls.getDeclaredField("score");
        scoreField.setAccessible(true);
        scoreField.set(obj, 100);

        /*
         * 获取属性
         */
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            String s = Modifier.toString(field.getModifiers());
            // 排除final修饰的属性
            if (!s.contains("final")) {
                field.setAccessible(true);
                // 通过filed获取设置属性
                System.out.printf("获取属性值,当前属性:%s,值:%s%n", field.getName(), field.get(obj));
                // obj对象属性值赋值给obj2
                field.set(obj2, field.get(obj));
            }
        }
        System.out.println("method1 obj:" + JSONObject.toJSONString(obj));
        System.out.println("method1 obj2:" + JSONObject.toJSONString(obj2));
    }

运行结果:

java 利用反射动态给类属性赋值 java反射设置对象属性_servlet

方式二

通过set方法:

public void method2() throws Exception {
        Class<StudentScore> cls = StudentScore.class;
        StudentScore obj = new StudentScore();

        /*
         * 设置属性
         */
        Method setName = cls.getMethod("setName", String.class);
        setName.invoke(obj, "李四");

        Method setSubject = cls.getMethod("setSubject", String.class);
        setSubject.invoke(obj, "语文");

        Method setScore = cls.getMethod("setScore", Integer.class);
        setScore.invoke(obj, 114);

        /*
         * 获取属性
         */
        Method getName = cls.getMethod("getName");
        System.out.printf("获取属性值,当前属性:%s,值:%s%n", "name", getName.invoke(obj));
        Method getSubject = cls.getMethod("getSubject");
        System.out.printf("获取属性值,当前属性:%s,值:%s%n", "subject", getSubject.invoke(obj));
        Method getScore = cls.getMethod("getScore");
        System.out.printf("获取属性值,当前属性:%s,值:%s%n", "score", getScore.invoke(obj));
        System.out.println("method2:" + JSONObject.toJSONString(obj));
    }

运行结果:

java 利用反射动态给类属性赋值 java反射设置对象属性_System_02

方式三

通过属性名:

public void method3() throws Exception {
        Class<StudentScore> cls = StudentScore.class;
        StudentScore obj = new StudentScore();
        /*
         * 设置属性
         */
        PropertyDescriptor namePd = new PropertyDescriptor("name", cls);
        Method writeMethod = namePd.getWriteMethod();
        writeMethod.invoke(obj, "王五");

        PropertyDescriptor subjectPd = new PropertyDescriptor("subject", cls);
        Method subjectMethod = subjectPd.getWriteMethod();
        subjectMethod.invoke(obj, "语文");

        PropertyDescriptor scorePd = new PropertyDescriptor("score", cls);
        Method scoreMethod = scorePd.getWriteMethod();
        scoreMethod.invoke(obj, 127);

        /*
         * 获取属性
         */
        Method nameRead = namePd.getReadMethod();
        System.out.printf("获取属性值,当前属性:%s,值:%s%n", "name", nameRead.invoke(obj));
        Method subjectRead = subjectPd.getReadMethod();
        System.out.printf("获取属性值,当前属性:%s,值:%s%n", "subject", subjectRead.invoke(obj));
        Method scoreRead = scorePd.getReadMethod();
        System.out.printf("获取属性值,当前属性:%s,值:%s%n", "score", scoreRead.invoke(obj));
        System.out.println("method3:" + JSONObject.toJSONString(obj));
    }

运行结果:

java 利用反射动态给类属性赋值 java反射设置对象属性_jvm_03

场景案例

场景:学生查询自己的语文考试成绩;

java 利用反射动态给类属性赋值 java反射设置对象属性_jvm_04

学生成绩对象实体类:

/**
 * 学生成绩实体
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class StudentScore {

    /**
     * 名称
     */
    private String name;
    /**
     * 科目
     */
    private String subject;
    /**
     * 成绩
     */
    private Integer score;

}

学生对象实体类:

/**
 * 学生-张三
 */
@Data
public class StudentZS extends StudentScore {
}
/**
 * 学生-李四
 *
 */
@Data
public class StudentLS extends StudentScore {
}
/**
 * 学生-王五
 */
@Data
public class StudentWW extends StudentScore {
}

测试:

@Test
public void testDemo() {
    StudentZS student1 = new StudentZS();
    student1.setName("张三");
    scoreSystem(student1, StudentZS.class);
    System.out.println("张三查询成绩结果:" + JSONObject.toJSONString(student1));

    StudentLS student2 = new StudentLS();
    student2.setName("李四");
    scoreSystem(student2, StudentLS.class);
    System.out.println("李四查询成绩结果:" + JSONObject.toJSONString(student2));

    StudentWW student3 = new StudentWW();
    student3.setName("王五");
    scoreSystem(student3, StudentWW.class);
    System.out.println("王五查询成绩结果:" + JSONObject.toJSONString(student3));
}

/**
  * 成绩系统
  *
  * @param t   学生
  * @param cls 学生类
  * @param <T> 泛型
  */
public <T> void scoreSystem(T t, Class<T> cls) {
    // 给传入对象赋值名称
    try {
        Class<? super T> superclass = cls.getSuperclass();
        Field nameField = superclass.getDeclaredField("name");
        Type genericType = nameField.getGenericType();
        String typeName = genericType.getTypeName();
        assert "java.lang.String".equals(typeName);
        nameField.setAccessible(true);
        String studentName = nameField.get(t).toString();
        int schoolReport = 0;
        switch (studentName) {
            case "张三":
                schoolReport = 100;
                break;
            case "李四":
                schoolReport = 114;
                break;
            case "王五":
                schoolReport = 127;
                break;
        }
        Field subjectField = superclass.getDeclaredField("subject");
        subjectField.setAccessible(true);
        subjectField.set(t, "语文");
        Field scoreField = superclass.getDeclaredField("score");
        scoreField.setAccessible(true);
        scoreField.set(t, schoolReport);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行结果:

java 利用反射动态给类属性赋值 java反射设置对象属性_jvm_05