【发布时间】:2019-06-13 13:27:19
【问题描述】:
我正在做一个图书馆管理项目,当我向图书馆注册会员时,“写入方法工作正常”。错误消息是“线程“AWT-EventQueue-0”中的异常 java.lang.ClassCastException:java.util.ArrayList 无法转换为 comsatslibrary.Personstrong text”
private class listener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String user = text.getText();
String pass = text1.getText();
boolean flag = true;
ArrayList<Person> personlist = HelperClass3.readAllData("person.txt");
if (e.getSource() == b) {
for (int i = 0; i < personlist.size(); i++) {
if ((user.equals((personlist.get(i).getFirstname()))) && (pass.equals(personlist.get(i).getPassword()))) {
flag = false;
}
}
if (flag == false) {
librarian l = new librarian();
}
} else{
JOptionPane.showMessageDialog(null, "Incorrect UserName or Password");
}
}
}
}
if ((user.equals((personlist.get(i).getFirstname()))) && (pass.equals(personlist.get(i).getPassword())))
这是错误行
我创建了一个通用帮助类
读取方法
public class HelperClass3 {
public static <T> ArrayList<T> readAllData(String path){
ArrayList<T> List = new ArrayList<T>(0);
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream(path));
boolean EOF = false;
while(!EOF) {
try {
T myObj = (T)inputStream.readObject();
List.add(myObj);
}catch (ClassNotFoundException e) {
System.out.println("Class not found");
}catch(EOFException e) {
EOF = true;
}
}
} catch(FileNotFoundException e) {
System.out.println("Cannot find file");
} catch(IOException e) {
System.out.println("IO Exception while opening stream");
} finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}catch(IOException e) {
System.out.println("IO Exception while closing file");
}
}
return List;
}
写法
public static<T> void addArrayListToFile(T s , String path) {
ArrayList<T> List = readAllData(path);
List.add(s);
ObjectOutputStream outputStream =null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(path));
for(int i = 0 ; i < List.size() ; i++) {
outputStream.writeObject(List.get(i));
}
} catch(IOException e) {
System.out.println("IO Exception while opening file");
}
finally {
try {
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
System.out.println("IO Exception while closing file");
}
}
}
}
T myObj = (T)inputStream.readObject();这就是问题所在。
【问题讨论】:
-
你的
Person类实现接口Serializable了吗? -
是的。 @Abra
-
你应该遵守 Java 命名约定:变量名用驼峰命名,类名用 PascalCase。
listener应该是Listener,librarian应该是Librarian,List应该是list。
标签: java exception arraylist classcastexception