JAVA 反射访问字段(含私有)的名称、类型、值

1.反射方法

public void test(Object o) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            IntrospectionException {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field f : fields) {
            // 设置允许访问私有字段的值
            f.setAccessible(true);
            // 取得字段名称
            String name = f.getName();
            // 取得字段类型的简单名称,java.lang.String-->String
            String type = f.getType().getSimpleName();
            // 取得字段值
            Object value = f.get(o);
            System.out.println(name + "," + type + "," + value.toString());
            // 重新设置字段的值[必须设置f.setAccessible(true),否则无法访问私有字段的值]
            if (name.equals("name") && value != null
                    && value.toString().equals("123")) {
                f.set(o, "456");
                System.out.println(f.get(o).toString());
            }

        }
原文地址:https://www.cnblogs.com/zhougaojun/p/3412079.html