美文网首页
【字段一致】父类转化为子类

【字段一致】父类转化为子类

作者: 蓝笔头 | 来源:发表于2021-08-27 09:55 被阅读0次

    测试结构

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class SuperClass {
        private long id;
        private String name;
    }
    
    @Data
    @ToString(callSuper = true)
    public class SubClass extends SuperClass {
    }
    

    转换

    • 1)直接转换
    public class TestMain {
        public static void main(String[] args) {
            SuperClass superClass = new SuperClass(1, "name");
            SubClass subClass = (SubClass) superClass;
            System.out.println(subClass);
        }
    }
    

    出现如下异常:

    Exception in thread "main" java.lang.ClassCastException: org.company.cast.SuperClass cannot be cast to org.company.cast.SubClass
        at org.company.TestMain.main(TestMain.java:9)
    
    • 2)序列化反序列化

    需引入 Jackson 依赖,可参考 Jackson 使用简介

    public class TestMain {
        public static void main(String[] args) {
            SuperClass superClass = new SuperClass(1, "name");
            String serialize = serialize(superClass);
            SubClass subClass = deserialize(serialize, SubClass.class);
            System.out.println(subClass);
        }
    
        private static final ObjectMapper objectMapper = new ObjectMapper();
    
        @SneakyThrows
        public static String serialize(Object obj) {
            return objectMapper.writeValueAsString(obj);
        }
    
        @SneakyThrows
        public static <T> T deserialize(String json, Class<T> clazz) {
            return objectMapper.readValue(json, clazz);
        }
    }
    

    控制台输出:

    SubClass(super=SuperClass(id=1, name=name))
    
    • 3)BeanUtils.copyProperties

    使用的是 Spring 的 spring-beans 版本。

    public class TestMain {
        public static void main(String[] args) {
            SuperClass superClass = new SuperClass(1, "name");
    
            SubClass subClass = new SubClass();
            BeanUtils.copyProperties(superClass, subClass);
            System.out.println(subClass);
        }
    }
    

    控制台输出:

    SubClass(super=SuperClass(id=1, name=name))
    

    API 差异

    • Spring spring-beans 版本:源对象 source 在前面,目标对象 target 在后面。
    package org.springframework.beans;
    
    public abstract class BeanUtils {
        public static void copyProperties(Object source, Object target) throws BeansException {
    }
    
    • Apache commons-beanutils 版本:源对象 orig 在后面,目标对象 dest 在前面。
    package org.apache.commons.beanutils;
    
    public class BeanUtils {
        public static void copyProperties(final Object dest, final Object orig)
    }
    

    参考

    相关文章

      网友评论

          本文标题:【字段一致】父类转化为子类

          本文链接:https://www.haomeiwen.com/subject/pfduiltx.html