简单封装beanUtils

**
 * 自定义封装bean规范
 */
public class BeanUtil {
    public static void setProperty(Object obj,String name,Object value) throws NoSuchFieldException, IllegalAccessException {
        Class aClass = obj.getClass();
        Field declaredField = aClass.getDeclaredField(name);
        declaredField.setAccessible(true);
        declaredField.set(obj,value);
    }

    /**
     * 获得字段属性的值
     * @param obj 字段的类
     * @param name 字段名字
     * @return 返回字段的类
     * @throws NoSuchFieldException 字段不存在异常
     * @throws IllegalAccessException 非法使用字段异常
     */
    public static Object getProperty(Object obj,String name) throws NoSuchFieldException, IllegalAccessException {
        Class aClass = obj.getClass();

        /**
         * 暴力反射得到字段的值
         */
        Field declaredField = aClass.getDeclaredField(name);
        declaredField.setAccessible(true);
        return declaredField.get(obj);
    }

    /**
     * 获取多个字段
     * @param src 原数组
     * @param dst 目标数组
     * @throws IllegalAccessException 非法使用字段异常
     */
    public static void copyProperty(Object src,Object dst) throws IllegalAccessException {
        Class aClass = src.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            // 从源数据对象中获取对应的数据
            Object o = field.get(src);
            // 设置当前数据到目标对象中
            field.set(dst, o);
        }
    }
}






你可能感兴趣的:(java)