父子类相互强转

父子类相互强转

问题引入

先来看一段代码

public class Main {
    public static void main(String[] args) throws IOException {
        Father child = new Child();
        child.setName("child");
        System.out.println(child);
        Father father = new Father();
        father.setName("father");
        Child child1 = (Child)father;
        System.out.println(child1);
    }

    static class Father {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Father{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    static class Child extends Father {
        private int age;

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

大家想想运行结果是什么 ?

想清楚了 请看结果

Father{name='child'}
Exception in thread "main" java.lang.ClassCastException: org.test.Main$Father cannot be cast to org.test.Main$Child
	at org.test.Main.main(Main.java:20)

惊不惊喜,意不意外,运行中竟然报错。

小结

  1. 子类转父类,无需强转,只能调用父类与子类中同时拥有的变量,
  2. 父类转子类,需要强转,并且转换能否成功取决于被转换的对象是否真的是目标类型的一员。
  3. https://stackoverflow.com/questions/4862960/explicit-casting-from-super-class-to-subclass

解决方案

基本思路转化成类型,在转换为子类。

利用FastJson转成JSON类型在转换成子类

public static void main(String[] args) throws IOException {
        Father child = new Child();
        child.setName("child");
        System.out.println(child);
        Father father = new Father();
        father.setName("father");
        JSON json = (JSON) JSON.toJSON(father);
        Child child1 = JSON.toJavaObject(json,Child.class);
        System.out.println(child1);

    }
运行结果
Father{name='child'}
Father{name='father'}

利用Gson转成JSON类型在转换成子类

public static void main(String[] args) throws IOException {
        Father child = new Child();
        child.setName("child");
        System.out.println(child);
        Father father = new Father();
        father.setName("father");
        Gson gson = new Gson();
        Child child1 = gson.fromJson(gson.toJson(father),Child.class);
        System.out.println(child1);

    }

这就是基本思路,当然方法有很多。大家可以多多尝试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值