How to copy properties from one Java bean to another?

前端 未结 8 1408
Happy的楠姐
Happy的楠姐 2020-12-17 15:53

I have a simple Java POJO that I would copy properties to another instance of same POJO class.

I know I can do that with BeanUtils.copyProperties() but I would like

8条回答
  •  离开以前
    2020-12-17 16:11

    You can achieve it using Java Reflection API.

    public static  void copy(T target, T source) throws Exception {
        Class clazz = source.getClass();
    
        for (Field field : clazz.getDeclaredFields()) {
            if (Modifier.isPrivate(field.getModifiers()))
                field.setAccessible(true);
            Object value = field.get(source);
            field.set(target, value);
        }
    }
    

提交回复
热议问题