java中两个不同类型的类转换

  • Post author:
  • Post category:java




java中两个不同类型的类转换

最近在做项目改造时,需要两个类型转换, 使用BeanUtils.copyProperties()转换时,发现属性的类型不一样是无法转换的,就自己实现了

maven依赖

   <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.4</version>
    </dependency>

User1.class

@Data
public class User1 {
  private String id;
  private String name;
  private BigDecimal money;
}


User2类及转换的方法

@Data
public class User2 {

  private Long id;
  private String name;
  private Long money;


  public static void main(String[] args) {

    testCopyProperties();
    testSet();
  }

  private static void testCopyProperties() {
    User1 user1 = new User1();
    user1.setId("1");
    user1.setName("张三");
    user1.setMoney(new BigDecimal("555"));
    long start = System.currentTimeMillis();
    User2 user2 = new User2();
    copyProperties(user1, user2);
    long end = System.currentTimeMillis();
    System.out.println("copyProperties的需要的时间:" + (end - start));
    System.out.println(user2);

  }


  private static void testSet() {
    User1 user1 = new User1();
    user1.setId("1");
    user1.setName("张三");
    user1.setMoney(new BigDecimal("555"));
    long start = System.currentTimeMillis();
    User2 user2 = new User2();
    user2.setId(Long.parseLong(user1.getId()));
    user2.setName(user1.getName());
    user2.setMoney(user1.getMoney().longValue());
    long end = System.currentTimeMillis();
    System.out.println("Set的需要的时间:" + (end - start));
    System.out.println(user2);
  }

  /**
   * 类型转换
   * @param source
   * @param target
   */
  public static void copyProperties(Object source, Object target) {
    Map<String, String> sourceMap = new HashMap<>();
    BeanMap beanMap = new BeanMap(source);
    for (Object key : beanMap.keySet()) {
      if ("class".equals(key)) {
        continue;
      }
      if (null != beanMap.get(key)) {
        sourceMap.put(key.toString(), beanMap.get(key).toString());
      }
    }
    BeanMap targetMap = new BeanMap(target);
    targetMap.putAll(sourceMap);
  }

}



结果截图

不过性能有点下降,偷懒是付出代价的,哈哈哈

在这里插入图片描述



版权声明:本文为qq_40198004原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。