我正在学习如何用 Java 进行序列化
我遇到的问题是代码可以工作,但我收到警告,我认为这是我投射它的方式。 我担心随着我的进步,它会给我带来问题。
未检查从对象到 ArrayList 的转换警告。
我正在尝试为我的简单项目创建一个帐户注册。
public class BankAccount implements Serializable {
public String username;
public String password;
public BankAccount() {
super();
// TODO Auto-generated constructor stub
}
public BankAccount(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
连载
BankAccount acc1 = new BankAccount("myuser", "mypass");
BankAccount acc2 = new BankAccount("abcd" , "1234");
BankAccount acc3 = new BankAccount("useracbc" , "pw1234");
ArrayList<BankAccount> accounts = new ArrayList<>();
accounts.add(acc1);
accounts.add(acc2);
accounts.add(acc3);
try {
FileOutputStream fileOut = new FileOutputStream("account.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
out.close();
System.out.println("Account successfully serialized");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
反序列化
ArrayList<BankAccount> myList = null;
try {
FileInputStream fileIn = new FileInputStream("account.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
myList = (ArrayList<BankAccount>) in.readObject();
fileIn.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(BankAccount list: myList) {
System.out.println(list.username);
System.out.println(list.password);
}
我尝试了 howtodoinjava 中的这个,但我仍然从铸造中收到相同的警告。
ArrayList<Employee> employeesList = null;
try (FileInputStream fis = new FileInputStream("employeeData");
ObjectInputStream ois = new ObjectInputStream(fis);) {
employeesList = (ArrayList) ois.readObject();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
}
//Verify list data
for (Employee employee : employeesList) {
System.out.println(employee);
}
关于未经检查的警告:一种解决方案可能是先简单地进行检查:
但是使用泛型类型擦除,您必须检查 ArrayList 类型以及所有元素。因此带有检查的代码可能类似于:
ArrayList<Employee> employeesList = new ArrayList<>();
try (FileInputStream fis = new FileInputStream("employeeData");
ObjectInputStream ois = new ObjectInputStream(fis);) {
Object readObject = ois.readObject();
if (readObject instanceof ArrayList readArray) {
for (Object element: readArray) {
if (element instanceof Employee employee) {
employeesList.add(employee);
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
}
这样你就只进行检查演员表。请注意:我没有进行错误处理。您应该处理读取对象不是 ArrayList 或不包含 Employee 元素的情况。
所以这可能是消除警告的有效解决方案。但这不是我推荐的解决方案!
相反:创建您自己的员工类。这将在内部存储列表,并且还将包含访问员工所需的所有代码。这样你就可以编写该类的一个实例,并且只需检查一个实例而不是检查所有员工。