尝试从我的文件中读取对象时,为什么会出现ClassCastException?

时间:2015-07-01 09:39:04

标签: arrays classcastexception serializable

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

错误可能在序列化类贷款中,但首先要看一下。因为如果我避免使用数组,它一切正常。我正在使用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();
}

}

1 个答案:

答案 0 :(得分:0)

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

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