简体   繁体   English

为什么我在尝试反序列化列表时收到 ClassCastException

[英]Why am I getting ClassCastException when trying to deserialize a list

Person class人 class

package model;

import java.io.Serializable;
import java.util.Objects;

public class Person implements Serializable {

    private String name;
    private String hobby;
    private Integer weight;
    private Integer age;

    public Person(String name, String hobby, Integer weight, Integer age) {
        this.name = name;
        this.hobby = hobby;
        this.weight = weight;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public Integer getWeight() {
        return weight;
    }
    public void setWeight(Integer weight) {
        this.weight = weight;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return
                "Name = '" + name + "'\n" +
                "Hobby = '" + hobby + "'\n" +
                "Weight = " + weight + "'\n" +
                "Age = " + age + "'\n";
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(name, person.name) && Objects.equals(hobby, person.hobby) && Objects.equals(weight, person.weight) && Objects.equals(age, person.age);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, hobby, weight, age);
    }
}

Serialization序列化

public static void serialization(List<Person> fileList){
    if(fileList.size() > 0) {
        try (ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream("dat/serialPersons.ser"))) {
            for (int i = 0; i < fileList.size(); i++) {
                if (fileList.get(i).getWeight() < 80) {
                    writer.writeObject(fileList.get(i));
                }
            }
            System.out.println("Serilization complete!");
        } catch (FileNotFoundException ex) {
            System.err.println(ex);
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
    else{
        System.out.println("List is empty!!");
    }
}

Deserialization反序列化

public static void deserialization(){
    try(ObjectInputStream objectReader
                = new ObjectInputStream(new FileInputStream("dat/serialPersons.ser"))) {
        List<Person> deserializedList = (List<Person>)objectReader.readObject();

        deserializedList.forEach(System.out::println);
    } catch(IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

I am trying to learn some FILE handling in java and been stuck on this for 2 hours, I did multiple examples and the same exception comes out.我正在尝试在 java 中学习一些 FILE 处理并在此停留了 2 个小时,我做了多个示例并且出现了相同的异常。 When I try to deserialize the whole file as a list, I get a class cast exception当我尝试将整个文件反序列化为列表时,出现 class 转换异常

Exception in thread "main" java.lang.ClassCastException: class model.Person cannot be cast to class java.util.List (model.Person is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
at main.Main.deserialization(Main.java:115)
at main.Main.main(Main.java:32)

If i use fileList.add(objectReader.readObject());如果我使用 fileList.add(objectReader.readObject()); I only get the first one from the file and it is working but I only get the first one.我只从文件中得到第一个,它正在工作,但我只得到第一个。

Any solution would be helpful.任何解决方案都会有所帮助。

EDIT: I used a whole list at once with conditioned objects and it all worked thanks编辑:我一次使用了整个列表和条件对象,这一切都有效,谢谢

I think you are writing "Person" object and reading list of "Person" objects.我认为您正在编写“Person” object 并阅读“Person”对象的列表。 "writer.writeObject(fileList.get(i));" “writer.writeObject(fileList.get(i));” that code would write a single Person because fileList.get(index) returns a single form of Person, however on reading part you are expecting that object to be list of "Person".该代码将编写单个 Person,因为 fileList.get(index) 返回单个形式的 Person,但是在阅读部分时,您期望 object 是“Person”列表。

For get rid of the issue tiny modification can save the flow, at least it might be worthy to try.为了摆脱这个问题,微小的修改可以节省流量,至少它可能值得一试。 But I'm not sure about your entire flow, it is just a suggestion.但我不确定你的整个流程,这只是一个建议。 Hopefully help you:)希望能帮到你:)

writer.writeObject(Arrays.asList(fileList.get(i)));

AS it: How do I write multiple objects to the serializable file and read them when the program is used again? AS it: 如何将多个对象写入可序列化文件并在再次使用程序时读取它们?

Write the array list directly.直接写数组列表。

Serialization序列化

public static void serialization(List<Person> fileList){
    if(fileList.size() > 0) {
        // First create the list of persons to save
        List<Person> personsToSave = new ArrayList<Person>();

        try (ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream("dat/serialPersons.ser"))) {
            for (int i = 0; i < fileList.size(); i++) {
                if (fileList.get(i).getWeight() < 80) {
                    personsToSave.add(fileList.get(i));
                }
            }
            // Then save
            writer.writeObject(personsToSave);
            System.out.println("Serilization complete!");
        } catch (FileNotFoundException ex) {
            System.err.println(ex);
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
    else{
        System.out.println("List is empty!!");
    }
}

The exception says you are trying to cast an instance of Person into a List(of Person).异常表示您正在尝试将 Person 的实例转换为 List(of Person)。 That's because readObject returns one Object(in this case one Person).这是因为 readObject 返回一个对象(在本例中为一个人)。 To make a list of Person, split the file by appropriate delimiter(comma, tab, etc), and read one Object at a time.要制作人员列表,请使用适当的分隔符(逗号、制表符等)拆分文件,并一次读取一个 Object。 Or you have to define another class that can work like an array of Person(call it PersonList for example), and use readObject to make a PersonList instance.或者您必须定义另一个 class 可以像 Person 数组一样工作(例如称为 PersonList),并使用 readObject 创建一个 PersonList 实例。 Or writing as ArrayList(or some other List implementations you like) and reading an ArrayList of Person can do the job.或者编写为 ArrayList(或您喜欢的其他一些 List 实现)并读取 Person 的 ArrayList 可以完成这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我得到这个ClassCastException? - Why am I getting this ClassCastException? 反序列化包含树形图的对象时,为什么会收到ClassCastException? - Why am I getting a ClassCastException when deserializing an object that contains a treemap? 为什么在生成 javadoc 时会收到 ClassCastException? - Why am I getting a ClassCastException when generating javadocs? 为什么在尝试将实体保存到列表时会收到 NullPointerException? - Why am i getting a NullPointerException when trying to save an entity to a list? 为什么我在这种情况下得到ClassCastException - why i am getting ClassCastException in this case 为什么我在AsyncTask中得到这个ClassCastException? - Why am I getting this ClassCastException in my AsyncTask? 为什么我在 Jenkins 构建中收到 ClassCastException - Why am I getting ClassCastException in Jenkins build 为什么我在这里得到ClassCastException? - Why am I getting a ClassCastException here? 尝试合并两个排序的链接列表时,为什么会得到一个空列表? - why am I getting an empty list when I am trying to merge two Sorted Linkedlists? 实例化一个类并将其强制转换为该类正在实现的接口时,为什么会出现ClassCastException? - Why am I getting ClassCastException when I instantiate a class and casting it to that interface which is being implemented by this class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM