Live2D

java反射的使用场景

当我们不知道传进来的对象有哪些属性并却还要赋值的时候,可以使用反射机制

class Test{

    public static void main(String[] args) throws Exception {
//        Student student = new Student("factory","北京",0);
//        getValue(student);


        Student student = new Student();
        Map<String, Object> map = new HashMap<>();
        map.put("name","胡图图");
        map.put("address","翻斗家园");
        map.put("status",1);
        Student student1=(Student)setValue(student,map) ;
        System.out.println(student1);
    }

    /**
     *
     * @param obj 传入的任意值
     * @throws IllegalAccessException
     */
    public static void getValue(Object obj) throws IllegalAccessException {
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            // 获取属性字段名
            System.out.println(field.getName());
            // 获取属性值
            System.out.println(field.get(obj));
        }
    }

    /**
     *
     * @param obj 传入的任意值
     * @param map  集合
     * @throws Exception
     */
    public static Object setValue(Object obj, Map<String,Object> map) throws Exception {
         Object newInstance=obj.getClass().getDeclaredConstructor().newInstance();
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            if (map.containsKey(field.getName())){
                field.set(newInstance,map.get(field.getName()));
            }
        }
        return newInstance;
    }
}
posted @ 2022-02-18 18:02  没有梦想的java菜鸟  阅读(229)  评论(0编辑  收藏  举报