Home > Mobile >  Java: reading objects from file into different derived classes
Java: reading objects from file into different derived classes

Time:11-09

I have class Employee, and two derived classes Hourly and Salary. Instantiations of those derived classes are placed in the same Array List called employeeList. When I read these objects from file using ois.readObject() how can I ensure the data ends up in the appropriate derived class? Thank you!

CodePudding user response:

I assume they are extensions of the Employee class ? If you have an array like this:

List<Employee> emps = ...

then you can do something like:

for (Employee e : emps) { if (e instanceof Hourly) ... }

You still need to check the elements. You can also use filter them like this:

emps.stream().filter(e -> e instanceof Hourly).collect(Collectors.toList())

CodePudding user response:

Note: I am not familiar with ObjectInputStream, so I am not exactly sure if this dynamic dispatch would work here, but I recommend giving this a try:

You could have your employee interface look like this:

interface Employee {
    // Whatever other methods you have defined
    
    void populateFieldsFromObject(Object obj);
}

Then each subclass would implement this method differently:

class HourlyEmployee implements Employee {

    // Other methods/fields...

    @override
    void populateFieldsFromObject(Object obj) {
        if (!(obj instanceof HourlyEmployee)) {
            throw new IllegalArugmentException("Object not of correct type");
        }
        HourlyEmployee objEmp = (HourlyEmployee)Object;
        this.hourly = objEmp.hourly;
    }
}

class SalaryEmployee implements Employee {

    // Other methods/fields...

    @override
    void populateFieldsFromObject(Object obj) {
        if (!(obj instanceof SalaryEmployee)) {
            throw new IllegalArugmentException("Object not of correct type");
        }
        SalaryEmployee objEmp = (SalaryEmployee)Object;
        this.salary = objEmp.salary;
    }
}

Then you can just iterate through your List of employees, and call: employee.populateFieldsFromObject(ois.readObject());, as Dynamic Dispatch should automatically determine which method to call based on the type of the object.

Let me know if this works.

  • Related