gpt4 book ai didi

java - 在没有 switch 语句的情况下反序列化子类。

转载 作者:行者123 更新时间:2023-11-29 05:41:53 25 4
gpt4 key购买 nike

这更像是一个软件工程问题。我有一个基类,以及扩展基类的类。我的目标是有一种更简洁的反序列化方式,比如 String。我目前的解决方案是获取这个序列化后的字符串,从预定的类型字段中提取'type',然后使用switch 语句调用相应子类的反序列化方法。有没有办法通过利用 Java 语言而不是 switch 语句来做到这一点?

public abstract class Base {
String type;
}

public class A extends Base{
public A(String serializedString){...}
}

public class B extends Base{
public B(String serializedString){...}
}

public class AuxMethods {

public static Base deserialize(String s){
String type = extractType(s); // gets the type from the serialized object string
Base deserialized = null;
switch(type){
case "A":
deserialized = new A(s);
break;
case "B":
deserialized = new B(s);
}

}

}

最佳答案

存储完整的类名(或假设所有类都在一个特定的包中),使用 Class.forName,然后查找字符串构造函数来创建对象。

关于java - 在没有 switch 语句的情况下反序列化子类。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com