How to cast one object into another

ghostrider :

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.

Andy Thomas :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145566&siteId=1