简体   繁体   中英

Java type casting for hibernate

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.

Eg

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            

    }
}

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