开发者

Java EE, casting Entity to Extended one!

开发者 https://www.devze.com 2023-03-08 22:47 出处:网络
Goodmorning. I have two entitis, User and User1 (which extends User with @Inheritance(strategy=InheritanceType.JOINED), adding some extra information like email, phonenumber and so on... attributes no

Goodmorning. I have two entitis, User and User1 (which extends User with @Inheritance(strategy=InheritanceType.JOINED), adding some extra information like email, phonenumber and so on... attributes not required for the entity User).

Now... User user is already persisted. I would like, in future, to be able to cast this user, providing that extra data, doing something like this:

User1 user1 = (User1)user;
user1.setEmail("email@email.com");

I've tried this solution, but of course... it doesn't work! (Casting Exception Returned).

Any idea? A开发者_JS百科ny help? Thanks.


Casting in Java doesn't work that way. You can only cast to Objects you actually extend from.

What you could do is provide a Copy Constructor in your extended Entity:

public ExtendedUser(BasicUser user){
    this.setFoo(user.getFoo());
    this.setBar(user.getBar());
}

But there's no way to cast something into something it doesn't extend. That's called type safety and is one of the most important aspects of Java.

Reference:

  • Java Language Specification: 5.1.6 Narrowing Reference Conversions
0

精彩评论

暂无评论...
验证码 换一张
取 消