开发者

Java type casting for hibernate

开发者 https://www.devze.com 2023-01-12 23:34 出处:网络
Yes, I know we can开发者_开发百科 upcast or downcast in Java.But the type of the instance doesn\'t really seems to be change and it\'s giving me a problem.

Yes, I know we can开发者_开发百科 upcast or downcast in Java. But the type of the instance doesn't really seems to be change and it's giving me a problem.

E.g.

class Foo{
int a, b; 
.. constructors, getters and setters
}

class FooDTO extends Foo {
...
}

FooDTO dto = FooDTO(1,2);
Foo parent = (Foo) dto;

in hibernate, when saving the "parent", it's still think that it's a DTO object and can't be saved. Can I really turn a child instance into a parent instance?


you can save the 'parent' by using hibernate's save(entityName, object) method. In this case the entityName is the fully qualified class name of 'parent'.


No u can't trun child into parent in this way. You have create the object for parent sperately.like, Foo parent new Foo(dto.getA(),dto.getB());


An object's type cannot be changed after it has been created. If you create a FooDTO object it will always be a FooDTO object.

When you cast you are telling the JVM that you are going to use a reference of type X to point at an object that you know is of type X.

class Parent {}
class Child extends Parent {}

class Test {
    public void stuff() {
        Parent p = new Parent(); // Parent reference, Parent object
        Parent p2 = new Child(); // Parent reference, Child object
        Child c = new Child();   // Child reference, Child object 


        Parent p2 = c; // no explicit cast required as you are up-casting
        Child c2 = (Child)p; // explicit cast required as you are down-casting. Throws ClassCastException as p does not point at a Child object
        Child c3 = (Child)p2; // explicit cast required as you are down-casting. Runs fine as p2 is pointong at a Child object
        String s1 = (String)p; // Does not compile as the compiler knows there is no way a Parent reference could be pointing at a String object            

    }
}
0

精彩评论

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