简体   繁体   中英

ClassCastException thrown at Runtime

I've been working on this simple Java program and at a point it throws a "ClassCastException" and I can't figure out why. What happens in the program is, it reads out of 2 text files and store them in Object Arraylists (Because I use the same method to read both files)

Later when I try to cast those objects to the custom data types I've made, the program throws this error. What am I doing wrong?

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.");
        }
    }

}

^^That calls for the Staff related menu.

            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!");
                        }
                    }

^^Here's where I get the exception, exactly at "Customer customer = (Customer) objs;"

I have two Classes Customer and Staff. And it throws " Exception in thread "main" java.lang.ClassCastException: Staff cannot be cast to Customer ", at run time. Compile time there are no issues.

readFile Method //Update

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;
}

What am I doing wrong here? Thanks in advance.

Since you have only two type of data type ( Staff and Customer )at your Object lists - staffs or clients , before type casting you can use the instanceof operator, like this -

for( Object obj : staffs){

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

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

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

So clients contains elements of Object type.

Inside the for-loop, when you try to cast objs (which is of Object type) to Customer , ClassCastException occurs.

Customer customer = (Customer) objs;

For the casting to be successful, you must make sure that the object to be cast is an instance of the subclass. If the superclass object is not an instance of the subclass, a runtime ClassCastException occurs. This can be made sure by using instanceof operator.

Here's an example to make things more clear:

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

There's no Exception. The reason is, o concrete type is Circle.

Now your case is somewhat like:

Object o;
(Circle)o.getRadius(); // Exception is thrown at this line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM