java实现相同属性名称及相似类型的pojo、dto、vo等互转操作

已应用于实际项目:

1.thrift对象与dto之间的互转

2.pojo与dto之间的互转

3.pojo与vo之间的互转

1.核心转换工具类,对特别复杂类型不做处理,因为业务场景还未覆盖

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])) {//如果不是基本类型并且泛型不一致,则需要继续转换
          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])) {//如果不是基本类型并且泛型不一致,则需要继续转换
          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);
  }

  /**
   * 判断变量是否有静态修饰符static
   * @param field
   * @return
   */
  public static boolean isStatic(Field field) {
    return (8 & field.getModifiers()) == 8;
  }
}

下面这个类是便于输出展示的,因为只是用于打印,所以不做效率考虑

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.产品类

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.商品类

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

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.属性枚举

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

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

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

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.颜色属性

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");
    }
  }
}

测试类,简单的做了一下输出查看

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);//正常输出,数组转换成功
  }

  @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实现相同属性名称及相似类型的pojo、dto、vo等互转操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Java 通过反射给实体类赋值操作

    表单提交这个方法是挺方便的,但在java来说就显得有些麻烦了, 怎么个麻烦呢,就是当你字段多的时候,你就得一个一个的获取其对应的值,这样代码量就多了起来,其代码量不说,维护也是一个问题. 所以就有了这样一个类,只需把request和实体类对象传进去就行了, 这样就会得到一个有值的实体类对象 下面是代码示例 import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Date; import ja

  • 利用Java反射机制实现对象相同字段的复制操作

    一.如何实现不同类型对象之间的复制问题? 1.为什么会有这个问题? 近来在进行一个项目开发的时候,为了隐藏后端数据库表结构.同时也为了配合给前端一个更友好的API接口文档(swagger API文档),我采用POJO来对应数据表结构,使用VO来给传递前端要展示的数据,同时使用DTO来进行请求参数的封装.以上是一个具体的场景,可以发现这样子一个现象:POJO.VO.DTO对象是同一个数据的不同视图,所以会有很多相同的字段,由于不同的地方使用不同的对象,无可避免的会存在对象之间的值迁移问题,迁移的一

  • Spring Data Jpa实现自定义repository转DTO

    近期项目中需要 关联 几张表再把字段转出来,在这里记录以下,我感觉网上写的都不太规范和清晰. @Entity @SqlResultSetMapping( name="TestMapping", entities = { @EntityResult( entityClass = com.xxx.xx.data.model.TestEntity.class, fields = { @FieldResult(name="id",column="id")

  • java实现相同属性名称及相似类型的pojo、dto、vo等互转操作

    已应用于实际项目: 1.thrift对象与dto之间的互转 2.pojo与dto之间的互转 3.pojo与vo之间的互转 1.核心转换工具类,对特别复杂类型不做处理,因为业务场景还未覆盖 package littlehow.convert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import

  • Mysql字段和java实体类属性类型匹配方式

    Mysql字段和java实体类属性类型匹配 参见下图: 数据库字段转实体类字段 DROP FUNCTION IF EXISTS f_spiltStr; CREATE FUNCTION `f_spiltStr`(DATA1 varchar(50)) RETURNS varchar(1000) CHARSET utf8 BEGIN SET @length = LENGTH(DATA1) - LENGTH(REPLACE(DATA1,'_','')); SET @i = 1; set @result

  • Java如何获取属性的注释信息详解

    前言 注解是JavaSE5.0开始提供的一项新特性,利用此特性可以通过特定的注解标签为程序提供一些描述性信息.这些描述性信息可以在编译或运行时为编译器.运行环境提供附加的信息,从而简化开发.本文将详细介绍Java获取属性注释信息的相关内容,下面来一起看看详细的实现代码 实例代码 1.数据模型 package com.example.demo; import java.util.List; /** * Description: * * @author jack * @date 2021/7/13

  • 详解Java继承中属性、方法和对象的关系

    大家都知道子类继承父类是类型的继承,包括属性和方法!如果子类和父类中的方法签名相同就叫覆盖!如果子类和父类的属性相同,父类就会隐藏自己的属性! 但是如果我用父类和子类所创建的引用指向子类所创建的对象,父类引用所调用子类对象中的属性值或方法的结果是什么呢? 看代码: public class FieldDemo { public static void main(String[] args){ Student t = new Student("Jack"); Person p = t;/

  • java springboot poi 从controller 接收不同类型excel 文件处理

    根据poi接收controller层的excel文件导入 可使用后缀名xls或xlsx格式的excel. 1.pom引入 <!-- poi 操作Excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <d

  • javascript获取函数名称、函数参数、对象属性名称的代码实例

    一.获取函数名称的3种实现方法实例1: 在js权威指南中看到的一个方法: Function.prototype.getName = function(){    return this.name || this.toString().match(/function\s*([^(]*)\(/)[1]} 实例2: 如果当前函数是有名函数,则返回其名字,如果是匿名函数则返回被赋值的函数变量名,如果是闭包中匿名函数则返回"anonymous". 复制代码 代码如下: var getFnName

  • 浅谈Java泛型让声明方法返回子类型的方法

    泛型典型的使用场景是集合.考虑到大多数情况下集合是同质的(同一类型),通过声明参数类型,可免去类型转换的麻烦.本文将讨论本人阅读Spring Security源码时遇到的一个关于泛型递归模式的问题. 声明方法返回子类型 在Spring Security的源码里有一个ProviderManagerBuilder接口,声明如下 public interface ProviderManagerBuilder<B extends ProviderManagerBuilder<B>> ext

  • Java ArrayList.toArray(T[]) 方法的参数类型是 T 而不是 E的原因分析

    前两天给同事做 code review,感觉自己对 Java 的 Generics 掌握得不够好,便拿出 <Effective Java>1 这本书再看看相关的章节.在 Item 24:Eliminate unchecked warnings 这一节中,作者拿 ArrayList 类中的 public <T> T[] toArray(T[] a) 方法作为例子来说明如何对变量使用 @SuppressWarnings annotation. ArrayList 是一个 generic

  • C#通过属性名称获取(读取)属性值的方法

    之前在开发一个程序,希望能够通过属性名称读取出属性值,但是由于那时候不熟悉反射,所以并没有找到合适的方法,做了不少的重复性工作啊! 然后今天我再上网找了找,被我找到了,跟大家分享一下. 其实原理并不复杂,就是通过反射利用属性名称去获取属性值,以前对反射不熟悉,所以没想到啊~ 不得不说反射是一种很强大的技术.. 下面给代码,希望能帮到有需要的人. using System; using System.Collections.Generic; using System.Linq; using Sys

  • java 文件下载支持中文名称的实例

    实例如下所示: /** * 文件下载 * @param filePath 文件路径 * @param fileName 文件名称 */ public void download(String filePath,String fileName){ try { //支持中文 fileName = URLEncoder.encode(fileName,"UTF-8"); HttpServletResponse response = ServletActionContext.getRespon

随机推荐