我想知道是否有某种方法可以反序列化对象并将其分配给接口(interface)中的属性?
我已经尝试了下面的代码,但我不知道如何用它检查“FileNotFound”异常,当然我不能只输入 throws FileNotFoundException
。
public interface Race_Attributes {
String[] FirstNames = (String[]) new ObjectInputStream(new FileInputStream("./res/binary_files/Human_FirstNameString[].ser")).readObject();
}
最佳答案
您可以通过将初始化代码包装在辅助方法中来处理初始化隐式静态接口(interface)属性时检查异常的问题。
public interface Race_Attributes {
String[] FirstNames = Deserializer.deserializeFirstNames();
}
final class Deserializer {
private Deserializer() {}
public static String[] deserializeFirstNames() {
try(ObjectInputStream in = new ObjectInputStream(
new FileInputStream(
"./res/binary_files/Human_FirstNameString[].ser"))) {
return (String[]) in.readObject();
}
catch( IOException | ClassNotFoundException e) {
return new String[0];
}
}
}
由于 Java 8 允许在接口(interface)中使用静态方法,因此您还可以将辅助方法 deserializeFirstNames
直接放置在接口(interface)中。但是,由于接口(interface)中的方法必须是公共(public)的,这会对接口(interface)的信息隐藏质量产生负面影响,因此在示例中我将其放置在单独的实用程序类中。
关于java - 在一行中反序列化对象以获得接口(interface)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53951710/