【问题标题】:Why do I get ClassCastException when trying to read objects from my file?尝试从文件中读取对象时,为什么会出现 ClassCastException?
【发布时间】:2015-07-01 17:54:41
【问题描述】:

我收到一个运行时错误,上面写着:线程“主”java.lang.ClassCastException 中的异常:lab07.Loan 无法转换为 [Llab07.Loan; 在 lab07.TestLoanClass.main(TestLoanClass.java:27)。

错误可能出在可序列化类 Loan 中,但请先看看这个。因为如果我避免使用数组,一切都会很好。我正在使用 Eclipse IDE。

public class TestLoanClass {

public static void main(String[] args) throws IOException,
        ClassNotFoundException {
    Loan[] loan = new Loan[5];

    ObjectOutputStream output = new ObjectOutputStream(
            new FileOutputStream("Exercise19_06.dat"));

    for (int i = 0; i < 5; i++) {
        loan[i] = new Loan(1.5 * i,i * 2,10000 * i);
        output.writeObject(loan[i]);
    }
    output.close();

    ObjectInputStream input = new ObjectInputStream(new FileInputStream(
            "Exercise19_06.dat"));


    //Conversion below is perfectly legal to type, but I get an error when 
    //I run the program. Appearently it has something with Object being 
    //cast to a Loan. Shouldn't the error show up while writing the code?

      Loan[] loanRead = (Loan[]) (input.readObject());

    //However, it work's just fine if I avoid using an array

    for (int j = 0; j < 5; j++) {

        System.out
                .printf("The loan was created on %s\n"
                        + "The monthly payment is %.2f\nThe total payment is %.2f\n",
                        loanRead[j].getLoanDate().toString(),
                        loanRead[j].getMonthlyPayment(),
                        loanRead[j].getTotalPayment());
    }

    input.close();
}

}

【问题讨论】:

  • 请用编程语言标记您的问题。

标签: arrays classcastexception serializable


【解决方案1】:

删除 Loan[] loanRead = (Loan[]) (input.readObject()); 并将 loan[j] = (Loan) (input.readObject()); 放入第二个 for 循环中。

当然,在 for 循环中使用 loan[j] 更改所有出现的 loanRead[j]

【讨论】:

  • 这工作非常好先生 :) 谢谢。我想我的错误是我试图只将一个对象读入整个通用数组或类似的东西。必须记住一次读取一个对象。
猜你喜欢
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2017-12-24
相关资源
最近更新 更多