屬性拷貝,通過反射把一個類的值傳給另外一個類

 

public class ClassUtil {

    /**
     * 適合兩個大量相同字段類的賦值
     * {@link Class#newInstance()} 該情況會返回null
     * @param source 數據來源
     * @param targetClass 類及構造函數爲public,非抽象類,接口,數據類,原始類型等。
     * @param <T>
     * @return
     */
    public static <T>T copy(Object source,Class<T> targetClass){
        try {
            T target = targetClass.newInstance();
            Class sourceClass = source.getClass();
            Field[] targetFields = targetClass.getDeclaredFields();
            for (Field field : targetFields) {
                String name = field.getName();
                //設爲true之後才能對private屬性進行操作
                field.setAccessible(true);
                Field sourceField;
                try {
                    sourceField = sourceClass.getDeclaredField(name);
                    sourceField.setAccessible(true);
                } catch (NoSuchFieldException e) {
                    continue;
                }
                Object value = sourceField.get(source);
                if (value != null){
                    if (field.getType().equals(sourceField.getType())){
                        field.set(target, value);
                    }else if (String.class.equals(field.getType())){
                        field.set(target, value.toString());
                    }
                }
            }
            return target;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

同樣,稍微改造一下,就可以給一個已有的實體增加新的值

    public static void copy(Object source,Object target){
        try {
            Class targetClass = target.getClass();
            Class sourceClass = source.getClass();
            Field[] targetFields = targetClass.getDeclaredFields();
            for (Field field : targetFields) {
                String name = field.getName();
                field.setAccessible(true);
                Field sourceField;
                try {
                    sourceField = sourceClass.getDeclaredField(name);
                    sourceField.setAccessible(true);
                } catch (NoSuchFieldException e) {
                    continue;
                }
                Object value = sourceField.get(source);
                if (value != null){
                    if (field.getType().equals(sourceField.getType())){
                        field.set(target, value);
                    }else if (String.class.equals(field.getType())){
                        field.set(target, value.toString());
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

這裏當字段的類不同時,僅簡單做了別的類到String的轉換。有興趣的可以在基礎上增加別的轉換,如數字之間的轉換等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章