简体   繁体   中英

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.

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

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)

Because Employee and User is completely two different object, so you cannot cast like your case

A simple example

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 extends User {
    //constructor
}

Then you can do this

Employee e = new Employee();
Object o = e;
User = (Employee) o;

Of course, In this case, you cannot do the opposite way: cast User to Employee

Hope this little example help you understand clearly about the case.

In java, an easy way to think about casting objects is: "Am I lying?" Ie if I cast the User to Employee, I'm saying the User is an Employee. Am I lying? If so, the cast will work. If not, then it wont. Now, according to your logic, you want all Employees to be Users. To establish an "is-a" relationship, you can use the word "extends"

class User{
//Your things
}
class Employee extends User{
//More employee-specific things
}

Now if you do

User john=new User(//args);

You can do

if(john instanceof Employee){//Make sure john is an employee
Employee johnEmployee=(Employee)john
}

All casting is is relabeling an object. But you can't lie about anything that isn't established when the object is made.

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