父子类相互强转
问题引入
先来看一段代码
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)
惊不惊喜,意不意外,运行中竟然报错。
小结
- 子类转父类,无需强转,只能调用父类与子类中同时拥有的变量,
- 父类转子类,需要强转,并且转换能否成功取决于被转换的对象是否真的是目标类型的一员。
- 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);
}
这就是基本思路,当然方法有很多。大家可以多多尝试。