java利用反射给动态对象赋值

1、实体工具类

public abstract class BaseUtils {
    private final static String SET = "set";
    private final static String GET = "get";
    private final static String IS = "is";
    /**
     * copyProperties
     * @param source
     * @param target
     * @throws Exception
     */
    public static void copyProperties (Object source,Object target)throws Exception{
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");

        Map valueMap = getFieldValueMap(source);
        setFieldValue(target,valueMap);
    }

    /**
     * 取出bean的值放到map中
     * @param bean
     * @return
     */
    private static Map getFieldValueMap(Object bean)throws Exception{
        Class beanClass = bean.getClass();
        //获取bean的所有方法
        Method[] methods = beanClass.getDeclaredMethods();
        //获取bean的所有字段
        Field[] fields = beanClass.getDeclaredFields();

        Map valueMap = new HashMap<>();
        for (Field field : fields) {
            try {
                //获取字段的类型
                String fieldType = field.getType().getSimpleName();//String  boolean
                String fieldType1 = field.getType().getName();//java.lang.String  boolean

                Method fieldGetMet;
                String fieldName = field.getName();
                if ("boolean".equals(fieldType)||"Boolean".equals(fieldType)){
                    if(!IS.equals(fieldName.substring(0,2))){
                        fieldName = IS + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
                    }else {
                        fieldName = IS + fieldName.substring(2,3).toUpperCase() + fieldName.substring(3);
                    }
                    //获取boolean的isXxx方法
                    fieldGetMet = beanClass.getMethod(fieldName,new Class[]{});
                }else{
                    //获取字段get的方法名
                    String fieldGetName = parGetOrSetName(fieldName,GET);
                    //获取字段的get方法
                    fieldGetMet = beanClass.getMethod(fieldGetName,new Class[]{});
                }
                //判断有没有该方法
                if (!checkMethod(methods,fieldGetMet))
                    continue;
                //获取字段的值
                Object fieldVal = fieldGetMet.invoke(bean,new Object[]{});
                if(fieldVal != null){
                    valueMap.put(field.getName(),fieldVal);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return valueMap;
    }

    /**
     * 把属性值放到bean
     * @param bean
     * @param valueMap
     */
    private static void setFieldValue(Object bean, Map valueMap)throws Exception{
        Class beanClass = bean.getClass();
        //获取bean的所有方法
        Method[] methods = beanClass.getDeclaredMethods();
        //获取bean的所有字段
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                //获取字段的类型
                String fieldType = field.getType().getSimpleName();
                String fieldName = field.getName();
                if (("boolean".equals(fieldType)||"Boolean".equals(fieldType))
                        && "is".equals(fieldName.substring(0, 2))){
                    fieldName = fieldName.substring(2);
                }
                //获取字段set的方法名
                String fieldSetName = parGetOrSetName(fieldName,SET);
                //获取字段的set方法
                Method fieldSetMet = beanClass.getMethod(fieldSetName,field.getType());
                //判断有没有该方法
                if (!checkMethod(methods,fieldSetMet))
                    continue;
                Object value = valueMap.get(field.getName());
                if (value != null)
                    fieldSetMet.invoke(bean,value);

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 拼接set或get方法
     * @param fieldName
     * @return
     */
   private static String parGetOrSetName(String fieldName,String met){
       if (null == fieldName || "".equals(fieldName)) {
           return null;
       }
       return met + fieldName.substring(0, 1).toUpperCase()
               + fieldName.substring(1);
   }

    /**
     * 判断类是否存在该方法
     * @param methods
     * @param met
     * @return
     */
   private static boolean checkMethod(Method[] methods,Method met){
       if (met == null)
           return false;
       for (Method method : methods) {
           if (met.equals(method))
               return true;
       }
       return false;
   }

}

2、测试

2.1、创建两个实体类

public class User implements Comparable{
    private int id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //生日
    private Date birthday;
    //身高
    private Double height;
    //身份证
    private long idCard;
    //是不是男生
    private boolean isMan;

    private Integer uu;
}

public class Person {
    private int id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //生日
    private Date birthday;
    //身高
    private Double height;
    //身份证
    private long idCard;
    //是不是男生
    private boolean isMan;

    private String pp;

}

2.2 test

public class Test {
    public static void main(String[] args) {
        String idCard = "16534964165316516";
        List list = new ArrayList<>();
        list.add("A");
        list.add("B");
        User user = new User();
        user.setId(1);
        //user.setName("小米");
        user.setAge(15);
        user.setHeight(1.70);
        user.setMan(true);
        user.setIdCard(Long.valueOf(idCard));
        user.setBirthday(new Date());
        user.setUu(0);
        user.setList(list);

        System.out.println(user);
        Person person = new Person();
        person.setPp("pp");
        person.setName("小米");
        System.out.println(person);
        try {
            EnyityUtils.copyProperties(user,person);
            System.out.println(user);
            System.out.println(person);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

2.3 结果

java利用反射给动态对象赋值_第1张图片

你可能感兴趣的:(java利用反射给动态对象赋值)