激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - java實現(xiàn)相同屬性名稱及相似類型的pojo、dto、vo等互轉操作

java實現(xiàn)相同屬性名稱及相似類型的pojo、dto、vo等互轉操作

2020-08-21 11:14little_how Java教程

這篇文章主要介紹了java實現(xiàn)相同屬性名稱及相似類型的pojo、dto、vo等互轉操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

已應用于實際項目:

1.thrift對象與dto之間的互轉

2.pojo與dto之間的互轉

3.pojo與vo之間的互轉

1.核心轉換工具類,對特別復雜類型不做處理,因為業(yè)務場景還未覆蓋

java" id="highlighter_455476">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package littlehow.convert;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * PojoConvertUtil
 *
 * @author littlehow
 * @time 2017-05-03 16:54
 */
public class PojoConvertUtil {
  private static Logger logger = LoggerFactory.getLogger(PojoConvertUtil.class);
  /**
   * 變量緩存
   */
  private static final Map<String, Map<String, Field>> cacheFields = new ConcurrentHashMap<>();
  private static final Set<Class> basicClass = new HashSet<>();
  static {
    basicClass.add(Integer.class);
    basicClass.add(Character.class);
    basicClass.add(Byte.class);
    basicClass.add(Float.class);
    basicClass.add(Double.class);
    basicClass.add(Boolean.class);
    basicClass.add(Long.class);
    basicClass.add(Short.class);
    basicClass.add(String.class);
    basicClass.add(BigDecimal.class);
  }
  /**
   * 將具有相同屬性的類型進行轉換
   * @param orig
   * @param <T>
   * @return
   */
  public static <T> T convertPojo(Object orig, Class<T> targetClass) {
    try {
      T target = targetClass.newInstance();
      /** 獲取源對象的所有變量 */
      Field[] fields = orig.getClass().getDeclaredFields();
      for (Field field : fields) {
        if (isStatic(field)) continue;
        /** 獲取目標方法 */
        Field targetField = getTargetField(targetClass, field.getName());
        if (targetField == null) continue;
        Object value = getFiledValue(field, orig);
        if (value == null) continue;
        Class type1 = field.getType();
        Class type2 = targetField.getType();
        //兩個類型是否相同
        boolean sameType = type1.equals(type2);
        if (isBasicType(type1)) {
          if (sameType) setFieldValue(targetField, target, value);
        } else if (value instanceof Map && Map.class.isAssignableFrom(type2)){//對map
          setMap((Map)value, field, targetField, target);
        } else if (value instanceof Set && Set.class.isAssignableFrom(type2)) {//對set
          setCollection((Collection)value, field, targetField, target);
        } else if (value instanceof List && List.class.isAssignableFrom(type2)) {//對list
          setCollection((Collection)value, field, targetField, target);
        } else if (value instanceof Enum && Enum.class.isAssignableFrom(type2)) {//對enum
          setEnum((Enum)value, field, targetField, target);
        } else if (value instanceof java.util.Date &&
            java.util.Date.class.isAssignableFrom(type2)) {//對日期類型,不處理如joda包之類的擴展時間,不處理calendar
          setDate((Date)value, targetField, type2, target, sameType);
        }
      }
      return target;
    } catch (Throwable t) {
      logger.error("轉換失敗:" + t.getMessage());
      throw new RuntimeException(t.getMessage());
    }
  }
 
  /**
   * 獲取字段值
   * @param field
   * @param obj
   * @return
   */
  private static Object getFiledValue(Field field, Object obj) throws IllegalAccessException {
    //獲取原有的訪問權限
    boolean access = field.isAccessible();
    try {
      //設置可訪問的權限
      field.setAccessible(true);
      return field.get(obj);
    } finally {
      //恢復訪問權限
      field.setAccessible(access);
    }
  }
 
  /**
   * 設置方法值
   * @param field
   * @param obj
   * @param value
   * @throws IllegalAccessException
   */
  private static void setFieldValue(Field field, Object obj, Object value) throws IllegalAccessException {
    //獲取原有的訪問權限
    boolean access = field.isAccessible();
    try {
      //設置可訪問的權限
      field.setAccessible(true);
      field.set(obj, value);
    } finally {
      //恢復訪問權限
      field.setAccessible(access);
    }
  }
 
  /**
   * 轉換list
   * @param orig
   * @param targetClass
   * @param <T>
   * @return
   */
  public static <T> List<T> convertPojos(List orig, Class<T> targetClass) {
    List<T> list = new ArrayList<>(orig.size());
    for (Object object : orig) {
      list.add(convertPojo(object, targetClass));
    }
    return list;
  }
 
  /**
   * 設置Map
   * @param value
   * @param origField
   * @param targetField
   * @param targetObject
   * @param <T>
   */
  private static <T> void setMap(Map value, Field origField, Field targetField, T targetObject) throws IllegalAccessException, InstantiationException{
    Type origType = origField.getGenericType();
    Type targetType = targetField.getGenericType();
    if (origType instanceof ParameterizedType && targetType instanceof ParameterizedType) {//泛型類型
      ParameterizedType origParameterizedType = (ParameterizedType)origType;
      Type[] origTypes = origParameterizedType.getActualTypeArguments();
      ParameterizedType targetParameterizedType = (ParameterizedType)targetType;
      Type[] targetTypes = targetParameterizedType.getActualTypeArguments();
      if (origTypes != null && origTypes.length == 2 && targetTypes != null && targetTypes.length == 2) {//正常泛型,查看第二個泛型是否不為基本類型
        Class clazz = (Class)origTypes[1];
        if (!isBasicType(clazz) && !clazz.equals(targetTypes[1])) {//如果不是基本類型并且泛型不一致,則需要繼續(xù)轉換
          Set<Map.Entry> entries = value.entrySet();
          Map targetMap = value.getClass().newInstance();
          for (Map.Entry entry : entries) {
            targetMap.put(entry.getKey(), convertPojo(entry.getValue(), (Class) targetTypes[1]));
          }
          setFieldValue(targetField, targetObject, targetMap);
          return;
        }
      }
    }
    setFieldValue(targetField, targetObject, value);
  }
 
  /**
   * 設置集合
   * @param value
   * @param origField
   * @param targetField
   * @param targetObject
   * @param <T>
   * @throws IllegalAccessException
   * @throws InstantiationException
   */
  private static <T> void setCollection(Collection value, Field origField, Field targetField, T targetObject) throws IllegalAccessException, InstantiationException{
    Type origType = origField.getGenericType();
    Type targetType = targetField.getGenericType();
    if (origType instanceof ParameterizedType && targetType instanceof ParameterizedType) {//泛型類型
      ParameterizedType origParameterizedType = (ParameterizedType)origType;
      Type[] origTypes = origParameterizedType.getActualTypeArguments();
      ParameterizedType targetParameterizedType = (ParameterizedType)targetType;
      Type[] targetTypes = targetParameterizedType.getActualTypeArguments();
      if (origTypes != null && origTypes.length == 1 && targetTypes != null && targetTypes.length == 1) {//正常泛型,查看第二個泛型是否不為基本類型
        Class clazz = (Class)origTypes[0];
        if (!isBasicType(clazz) && !clazz.equals(targetTypes[0])) {//如果不是基本類型并且泛型不一致,則需要繼續(xù)轉換
          Collection collection = value.getClass().newInstance();
          for (Object obj : value) {
            collection.add(convertPojo(obj, (Class) targetTypes[0]));
          }
          setFieldValue(targetField, targetObject, collection);
          return;
        }
      }
    }
    setFieldValue(targetField, targetObject, value);
  }
 
  /**
   * 設置枚舉類型
   * @param value
   * @param origField
   * @param targetField
   * @param targetObject
   * @param <T>
   */
  private static <T> void setEnum(Enum value, Field origField, Field targetField, T targetObject) throws Exception{
    if (origField.equals(targetField)) {
      setFieldValue(targetField, targetObject, value);
    } else {
      //枚舉類型都具有一個static修飾的valueOf方法
      Method method = targetField.getType().getMethod("valueOf", String.class);
      setFieldValue(targetField, targetObject, method.invoke(null, value.toString()));
    }
  }
 
  /**
   * 設置日期類型
   * @param value
   * @param targetField
   * @param targetFieldType
   * @param targetObject
   * @param <T>
   */
  private static <T> void setDate(Date value, Field targetField, Class targetFieldType, T targetObject, boolean sameType) throws IllegalAccessException {
    Date date = null;
    if (sameType) {
      date = value;
    } else if (targetFieldType.equals(java.sql.Date.class)) {
      date = new java.sql.Date(value.getTime());
    } else if (targetFieldType.equals(java.util.Date.class)) {
      date = new Date(value.getTime());
    } else if (targetFieldType.equals(java.sql.Timestamp.class)) {
      date = new java.sql.Timestamp(value.getTime());
    }
    setFieldValue(targetField, targetObject, date);
  }
 
  /**
   * 獲取適配方法
   * @param clazz
   * @param fieldName
   * @return
   */
  public static Field getTargetField(Class clazz, String fieldName) {
    String classKey = clazz.getName();
    Map<String, Field> fieldMap = cacheFields.get(classKey);
    if (fieldMap == null) {
      fieldMap = new HashMap<>();
      Field[] fields = clazz.getDeclaredFields();
      for (Field field : fields) {
        if (isStatic(field)) continue;
        fieldMap.put(field.getName(), field);
      }
      cacheFields.put(classKey, fieldMap);
    }
    return fieldMap.get(fieldName);
  }
 
  /**
   * 確實是否為基礎類型
   * @param clazz
   * @return
   */
  public static boolean isBasicType(Class clazz) {
    return clazz.isPrimitive() || basicClass.contains(clazz);
  }
 
  /**
   * 判斷變量是否有靜態(tài)修飾符static
   * @param field
   * @return
   */
  public static boolean isStatic(Field field) {
    return (8 & field.getModifiers()) == 8;
  }
}

下面這個類是便于輸出展示的,因為只是用于打印,所以不做效率考慮

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package littlehow.convert;
 
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * SimpleToStringParent
 *
 * @author littlehow
 * @time 2017-05-04 10:40
 */
public class SimpleToStringParent {
 
  @Override
  public String toString() {
    try {
      StringBuilder stringBuilder = new StringBuilder("{");
      Field[] fields = this.getClass().getDeclaredFields();
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      for (Field field : fields) {
        Object value = getFiledValue(field, this);
        if (value == null) continue;
        if (value instanceof Date) {
          //這里也可以直接轉為時間戳
          value = dateFormat.format((Date)value);
        }
        stringBuilder.append(field.getName()).append("=").append(value).append(",");
      }
      String returnValue = stringBuilder.toString();
      if (returnValue.length() > 1) {
        returnValue = returnValue.substring(0, returnValue.length() - 1);
      }
      return this.getClass().getSimpleName() + returnValue + "}";
    } catch (Exception e) {
      // skip
    }
    return this.getClass().getSimpleName() + "{}";
  }
 
  /**
   * 獲取屬性值
   * @param field
   * @param obj
   * @return
   * @throws IllegalAccessException
   */
  private Object getFiledValue(Field field, Object obj) throws IllegalAccessException {
    //獲取原有的訪問權限
    boolean access = field.isAccessible();
    try {
      //設置可訪問的權限
      field.setAccessible(true);
      return field.get(obj);
    } finally {
      //恢復訪問權限
      field.setAccessible(access);
    }
  }
}

測試用的4個pojo

1.產品類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package littlehow.convert.pojo;
 
import littlehow.convert.SimpleToStringParent;
 
import java.util.List;
 
/**
 * Product
 *
 * @author littlehow
 * @time 2017-05-04 09:15
 */
public class Product extends SimpleToStringParent {
  private Integer productId;
  private String generalName;
  private String factoryName;
  private String unit;
  private String specification;
  private Integer category;
  private List<Item> items;
 
  public Integer getProductId() {
    return productId;
  }
 
  public void setProductId(Integer productId) {
    this.productId = productId;
  }
 
  public String getGeneralName() {
    return generalName;
  }
 
  public void setGeneralName(String generalName) {
    this.generalName = generalName;
  }
 
  public String getFactoryName() {
    return factoryName;
  }
 
  public void setFactoryName(String factoryName) {
    this.factoryName = factoryName;
  }
 
  public String getUnit() {
    return unit;
  }
 
  public void setUnit(String unit) {
    this.unit = unit;
  }
 
  public String getSpecification() {
    return specification;
  }
 
  public void setSpecification(String specification) {
    this.specification = specification;
  }
 
  public List<Item> getItems() {
    return items;
  }
 
  public void setItems(List<Item> items) {
    this.items = items;
  }
 
  public Integer getCategory() {
    return category;
  }
 
  public void setCategory(Integer category) {
    this.category = category;
  }
}

2.商品類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package littlehow.convert.pojo;
 
 
import littlehow.convert.SimpleToStringParent;
 
import java.util.Date;
import java.util.List;
 
/**
 * Item
 *
 * @author littlehow
 * @time 2017-05-04 09:15
 */
public class Item extends SimpleToStringParent {
  private Long itemId;
  private String itemName;
  private Byte status;
  private Boolean deleted;
  private Date createTime;
  private List<Sku> skus;
 
  public Long getItemId() {
    return itemId;
  }
 
  public void setItemId(Long itemId) {
    this.itemId = itemId;
  }
 
  public String getItemName() {
    return itemName;
  }
 
  public void setItemName(String itemName) {
    this.itemName = itemName;
  }
 
  public Byte getStatus() {
    return status;
  }
 
  public void setStatus(Byte status) {
    this.status = status;
  }
 
  public Boolean getDeleted() {
    return deleted;
  }
 
  public void setDeleted(Boolean deleted) {
    this.deleted = deleted;
  }
 
  public Date getCreateTime() {
    return createTime;
  }
 
  public void setCreateTime(Date createTime) {
    this.createTime = createTime;
  }
 
  public List<Sku> getSkus() {
    return skus;
  }
 
  public void setSkus(List<Sku> skus) {
    this.skus = skus;
  }
}

3.最小庫存單位sku

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package littlehow.convert.pojo;
 
import littlehow.convert.SimpleToStringParent;
 
import java.lang.reflect.Field;
 
/**
 * Sku
 *
 * @author littlehow
 * @time 2017-05-04 09:15
 */
public class Sku extends SimpleToStringParent {
  private Long skuId;
  private Byte status;
  private Boolean deleted;
  private Double price;
  private Double promoPrice;
  private Integer inventory;
  private Integer minBuy;
  private Integer blockInventory;
  private Color skuColor;
 
  public Long getSkuId() {
    return skuId;
  }
 
  public void setSkuId(Long skuId) {
    this.skuId = skuId;
  }
 
  public Byte getStatus() {
    return status;
  }
 
  public void setStatus(Byte status) {
    this.status = status;
  }
 
  public Boolean getDeleted() {
    return deleted;
  }
 
  public void setDeleted(Boolean deleted) {
    this.deleted = deleted;
  }
 
  public Double getPrice() {
    return price;
  }
 
  public void setPrice(Double price) {
    this.price = price;
  }
 
  public Double getPromoPrice() {
    return promoPrice;
  }
 
  public void setPromoPrice(Double promoPrice) {
    this.promoPrice = promoPrice;
  }
 
  public Integer getInventory() {
    return inventory;
  }
 
  public void setInventory(Integer inventory) {
    this.inventory = inventory;
  }
 
  public Integer getMinBuy() {
    return minBuy;
  }
 
  public void setMinBuy(Integer minBuy) {
    this.minBuy = minBuy;
  }
 
  public Integer getBlockInventory() {
    return blockInventory;
  }
 
  public void setBlockInventory(Integer blockInventory) {
    this.blockInventory = blockInventory;
  }
 
  public Color getSkuColor() {
    return skuColor;
  }
 
  public void setSkuColor(Color skuColor) {
    this.skuColor = skuColor;
  }
}

4.屬性枚舉

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package littlehow.convert.pojo;
 
/**
 * Color
 *
 * @author littlehow
 * @time 2017-05-04 09:21
 */
public enum Color {
  BLACK(1),
  RED(2),
  BLUE(3),
  GREEN(4);
  public final int value;
  Color(int value) {
    this.value = value;
  }
 
  public static Color valueOf(int value) {
    switch (value) {
      case 1 : return BLACK;
      case 2 : return RED;
      case 3 : return BLUE;
      case 4 : return GREEN;
      default : throw new IllegalArgumentException(value + " is not a enum value");
    }
  }
}

轉換用的dto,當然也可以將dto作為轉換源

1.產品dto

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package littlehow.convert.dto;
 
import littlehow.convert.SimpleToStringParent;
import littlehow.convert.pojo.Item;
 
import java.util.List;
 
/**
 * ProductDto
 *
 * @author littlehow
 * @time 2017-05-04 09:16
 */
public class ProductDto extends SimpleToStringParent {
  private Integer productId;
  private String generalName;
  private String factoryName;
  private String unit;
  private String specification;
  private Integer category;
  private List<ItemDto> items;
 
  public Integer getProductId() {
    return productId;
  }
 
  public void setProductId(Integer productId) {
    this.productId = productId;
  }
 
  public String getGeneralName() {
    return generalName;
  }
 
  public void setGeneralName(String generalName) {
    this.generalName = generalName;
  }
 
  public String getFactoryName() {
    return factoryName;
  }
 
  public void setFactoryName(String factoryName) {
    this.factoryName = factoryName;
  }
 
  public String getUnit() {
    return unit;
  }
 
  public void setUnit(String unit) {
    this.unit = unit;
  }
 
  public String getSpecification() {
    return specification;
  }
 
  public void setSpecification(String specification) {
    this.specification = specification;
  }
 
  public List<ItemDto> getItems() {
    return items;
  }
 
  public void setItems(List<ItemDto> items) {
    this.items = items;
  }
 
  public Integer getCategory() {
    return category;
  }
 
  public void setCategory(Integer category) {
    this.category = category;
  }
}

2.商品dto

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package littlehow.convert.dto;
 
import littlehow.convert.SimpleToStringParent;
import littlehow.convert.pojo.Sku;
 
import java.util.Date;
import java.util.List;
 
/**
 * ItemDto
 *
 * @author littlehow
 * @time 2017-05-04 09:16
 */
public class ItemDto extends SimpleToStringParent {
  private Integer itemId;
  private String itemName;
  private Byte status;
  private Boolean deleted;
  private Date createTime;
  private List<SkuDto> skus;
 
  public Integer getItemId() {
    return itemId;
  }
 
  public void setItemId(Integer itemId) {
    this.itemId = itemId;
  }
 
  public String getItemName() {
    return itemName;
  }
 
  public void setItemName(String itemName) {
    this.itemName = itemName;
  }
 
  public Byte getStatus() {
    return status;
  }
 
  public void setStatus(Byte status) {
    this.status = status;
  }
 
  public Boolean getDeleted() {
    return deleted;
  }
 
  public void setDeleted(Boolean deleted) {
    this.deleted = deleted;
  }
 
  public Date getCreateTime() {
    return createTime;
  }
 
  public void setCreateTime(Date createTime) {
    this.createTime = createTime;
  }
 
  public List<SkuDto> getSkus() {
    return skus;
  }
 
  public void setSkus(List<SkuDto> skus) {
    this.skus = skus;
  }
}

3.skudto

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package littlehow.convert.dto;
 
import littlehow.convert.SimpleToStringParent;
import littlehow.convert.pojo.Color;
 
/**
 * SkuDto
 *
 * @author littlehow
 * @time 2017-05-04 09:16
 */
public class SkuDto extends SimpleToStringParent {
  private Long skuId;
  private Byte status;
  private Boolean deleted;
  private Double price;
  private Double promoPrice;
  private Integer inventory;
  private Integer minBuy;
  private Integer blockInventory;
  private ColorDto skuColor;
 
  public Long getSkuId() {
    return skuId;
  }
 
  public void setSkuId(Long skuId) {
    this.skuId = skuId;
  }
 
  public Byte getStatus() {
    return status;
  }
 
  public void setStatus(Byte status) {
    this.status = status;
  }
 
  public Boolean getDeleted() {
    return deleted;
  }
 
  public void setDeleted(Boolean deleted) {
    this.deleted = deleted;
  }
 
  public Double getPrice() {
    return price;
  }
 
  public void setPrice(Double price) {
    this.price = price;
  }
 
  public Double getPromoPrice() {
    return promoPrice;
  }
 
  public void setPromoPrice(Double promoPrice) {
    this.promoPrice = promoPrice;
  }
 
  public Integer getInventory() {
    return inventory;
  }
 
  public void setInventory(Integer inventory) {
    this.inventory = inventory;
  }
 
  public Integer getMinBuy() {
    return minBuy;
  }
 
  public void setMinBuy(Integer minBuy) {
    this.minBuy = minBuy;
  }
 
  public Integer getBlockInventory() {
    return blockInventory;
  }
 
  public void setBlockInventory(Integer blockInventory) {
    this.blockInventory = blockInventory;
  }
 
  public ColorDto getSkuColor() {
    return skuColor;
  }
 
  public void setSkuColor(ColorDto skuColor) {
    this.skuColor = skuColor;
  }
}

4.顏色屬性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package littlehow.convert.dto;
 
/**
 * ColorDto
 *
 * @author littlehow
 * @time 2017-05-04 09:21
 */
public enum ColorDto {
  BLACK(1),
  RED(2),
  BLUE(3),
  GREEN(4);
  public final int value;
  ColorDto(int value) {
    this.value = value;
  }
 
  public static ColorDto valueOf(int value) {
    switch (value) {
      case 1 : return BLACK;
      case 2 : return RED;
      case 3 : return BLUE;
      case 4 : return GREEN;
      default : throw new IllegalArgumentException(value + " is not a enum value");
    }
  }
}

測試類,簡單的做了一下輸出查看

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package littlehow.convert.test;
 
import littlehow.convert.PojoConvertUtil;
import littlehow.convert.dto.ItemDto;
import littlehow.convert.dto.ProductDto;
import littlehow.convert.dto.SkuDto;
import littlehow.convert.pojo.Color;
import littlehow.convert.pojo.Item;
import littlehow.convert.pojo.Product;
import littlehow.convert.pojo.Sku;
import org.junit.Before;
import org.junit.Test;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * TransTest
 *
 * @author littlehow
 * @time 2017-05-04 10:44
 */
public class TransTest {
  private Product product;
 
  @Before
  public void init() {
    product = new Product();
    product.setCategory(123);
    product.setFactoryName("littlehow's shop");
    product.setGeneralName("littlehow's product");
    product.setProductId(1);
    product.setSpecification("16*2u");
    product.setUnit("box");
    List<Item> items = new ArrayList<>();
    for (int i=1; i<=5; i++) {
      Item item = new Item();
      item.setCreateTime(new Date());
      item.setDeleted(i % 3 == 0);
      item.setItemId((long) i);
      item.setItemName("littlehow's " + i + "th item");
      item.setStatus((byte) (i % 4));
      List<Sku> skus = new ArrayList<>();
      for (int j=1; j<=i; j++) {
        Sku sku = new Sku();
        sku.setSkuId((long)(j * (i + 5) * 3));
        sku.setStatus((byte) 1);
        sku.setDeleted(false);
        sku.setBlockInventory(5);
        sku.setInventory(j * 100);
        sku.setMinBuy(j * 5);
        sku.setPrice(Double.valueOf(j * 103));
        sku.setPromoPrice(Double.valueOf(j * 101));
        sku.setSkuColor(Color.valueOf(j % 4 + 1));
        skus.add(sku);
      }
      item.setSkus(skus);
      items.add(item);
    }
    product.setItems(items);
  }
 
  @Test
  public void test() {
    System.out.println(product);//正常輸出
    System.out.println("========================");
    ProductDto productDto = PojoConvertUtil.convertPojo(product, ProductDto.class);
    System.out.println(productDto);//正常輸出,證明轉換正常
    System.out.println("=========================");
    List<Item> items = product.getItems();
    List<ItemDto> itemDtos = PojoConvertUtil.convertPojos(items, ItemDto.class);
    System.out.println(itemDtos);//正常輸出,數(shù)組轉換成功
  }
 
  @Test
  public void test1() {
    Sku sku = product.getItems().get(0).getSkus().get(0);
    System.out.println(sku);//正常輸出
    System.out.println("=========================");
    SkuDto skuDto = PojoConvertUtil.convertPojo(sku, SkuDto.class);
    System.out.println(skuDto);
  }
}

能快速完成基礎類之間的互轉

以上這篇java實現(xiàn)相同屬性名稱及相似類型的pojo、dto、vo等互轉操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/w172087242/article/details/71172234

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产剧情在线观看一区二区 | 黄色网址在线免费 | 久久成人午夜视频 | 国产亚洲精品久久久久久久久久 | 全黄裸片武则天艳史 | 爱爱插插视频 | 日韩黄色免费电影 | 免费高清一级欧美片在线观看 | 奶子吧naiziba.cc免费午夜片在线观看 | 日韩视频一区二区在线观看 | 成人午夜在线观看视频 | 国内精品久久久久影院不卡 | 性大片免费看 | 欧美黑人伦理 | 黄网站免费入口 | 精品国产一区二区三区免费 | 亚洲国产超高清a毛毛片 | 12av毛片| 婷婷精品国产一区二区三区日韩 | 日本精品免费观看 | 亚洲精品aaaaa | 久久久一区二区三区四区 | 毛片在线免费视频 | 国产a级网站 | 55夜色66夜色国产精品视频 | 国产一级毛片视频在线! | 精品国产一区二区三区在线观看 | 国产视频第一区 | 国产大片中文字幕在线观看 | 久久精品之| 色淫网站免费视频 | 亚洲视频在线一区二区 | 精品久久久久久久久久久久包黑料 | 日韩在线播放一区二区 | 日韩视频高清 | 午夜在线小视频 | 黄色影院一级片 | 一级大片视频 | 九九热精品在线视频 | 在线观看国产网站 | 毛片在线免费播放 |