在运行时抛出ClassCastException

时间:2015-08-29 14:52:57

标签: java exception-handling classcastexception

我一直致力于这个简单的Java程序,并且它会抛出一个" ClassCastException"我无法弄清楚原因。程序中发生的是,它读取2个文本文件并将它们存储在对象Arraylists中(因为我使用相同的方法来读取这两个文件)

稍后当我尝试将这些对象强制转换为我已经创建的自定义数据类型时,程序会抛出此错误。我做错了什么?

public void staffFunctions() {
    ArrayList<Object> staffs = TextFileHandler.readFile(staffText,userState);

    for(Object obj: staffs) {
        Staff staff = (Staff) obj;
        if (staff.getUsername().equals(username) && staff.getPassword().equals(password)) {
            staffMenu(staff);
        } else {
            System.out.println("Username/Password Invalid.");
        }
    }

}

^^这需要员工相关菜单。

            ArrayList<Object> clients = TextFileHandler.readFile(accText, userState);
        System.out.print("Enter Client Username > ");
                    String usernameClient = input.next();
                    System.out.print("Enter amount > ");
                    int amount = input.nextInt();

                    for(Object objs: clients) {
                        Customer customer = (Customer) objs;
                        if(customer.getUsername().equals(usernameClient)){
                            ClientFunctions.withdraw(customer, username, amount);
                        } else {
                            System.out.println("Invalid Client Username!");
                        }
                    }

^^这里是我获得例外的地方,正是在&#34;客户客户=(客户)objs;&#34;

我有两个班级客户和员工。它会引发&#34; 线程中的异常&#34; main&#34; java.lang.ClassCastException:在运行时无法将人员强制转换为客户&#34;。编译时间没有问题。

readFile方法//更新

public static ArrayList<Object> readFile(String fileName, int userState) {
    String line = null;
    ArrayList<Object> elements = new ArrayList<>();

    try {
        fileReader = new java.io.FileReader("src/" + fileName);
        bufferedReader = new BufferedReader(fileReader);

        while ((line = bufferedReader.readLine()) != null) {
            String element[] = line.split(" ");
            if (userState == 1) {
                Customer customer = new Customer(element[1], element[3], element[5], element[7], element[9], element[11]);
                elements.add(customer);
            } else {
                Staff staff = new Staff(element[1], element[3]);
                elements.add(staff);
            }
        }
        bufferedReader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");
    } catch (IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");
    }

    return elements;
}

我在这里做错了什么?提前谢谢。

2 个答案:

答案 0 :(得分:1)

由于您在Staff列表中只有两种类型的数据类型(CustomerObject) - staffsclients,因此在输入您之前可以使用instanceof运算符,如下所示 -

for( Object obj : staffs){

   if(obj instance of Staff){
      Staff staff = (Staff) obj;
   }

   if(obj instance of Customer){
      Customer Customer = (Customer) obj;
   }
   ...

}

答案 1 :(得分:1)

ArrayList<Object> clients = TextFileHandler.readFile(accText, userState);

因此clients包含Object类型的元素。

在for循环中,当您尝试将objsObject类型)强制转换为Customer时,会发生ClassCastException。

Customer customer = (Customer) objs;

为了使演员成功,你必须确保 要转换的对象是子类的实例。如果超类对象不是实例 在子类中,发生运行时ClassCastException。可以使用instanceof运算符确保这一点。

这是一个让事情更清晰的例子:

Object o = new Circle();
(Circle)o.getRadius(); // No exception at this point

没有例外。原因是,o具体类型是圆形。

现在你的情况有点像:

Object o;
(Circle)o.getRadius(); // Exception is thrown at this line
相关问题