Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast one object into another

I am a beginner in Java and have below 2 Beans/POJOS in my existing company application:

User

public class User {

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

}

Employee

public class Employee {


public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}

}

I want to cast User to Employee because in the application I would be receiving the User object in the one of the methods which is used for persisting into the database using hibernate3 xml mapping method. HIbernate mapping exists for the Employee object and not for User. Hence I tried the conversion using the below concept that everything in java is an object but still it is giving the RuntimeException of ClassCastException :

User u = new User(12,"johnson","pam",new Date());
Object o = u;
Employee e=(Employee)o;

Is there any other way to solve this problem? There is no option to change the existing class hierarchies or include any additional inheritance structure.

like image 501
ghostrider Avatar asked Oct 15 '25 18:10

ghostrider


2 Answers

You cannot cast objects at all in Java. You can cast a reference, to a type implemented by the referenced object.

What you can do is convert from one object to a new object. If you cannot modify the classes, you can write an external converter. For example:

public class EmployeeFactory {
    public static Employee toEmployee( User user ) {
        Employee emp = new Employee();
        emp.setUserId( user.getUserId() );
        emp.setUserName( user.getUserName());
        return emp;
    }
}
like image 172
Andy Thomas Avatar answered Oct 17 '25 07:10

Andy Thomas


You can't cast user object to an employee object as they don't have any relation. You should have some Mapper class which will map a User object to Employee Object.

class UserToEmployee{
   public Employee map(User user){
       Employee e = new Employee();
       e.setUserId(user.getUserId());
       // so on set all the required properties
      return e;
    }
}

Then use it like:

User u = new User(12,"johnson","pam",new Date());
UserToEmployee mapper = new UserToEmployee();
Employee e = mapper.map(u)
like image 34
Amit Bera Avatar answered Oct 17 '25 09:10

Amit Bera