2010-08-26 76 views
0

是的,我知道我们可以在Java中进行向上转换或向下转换。但是实例的类型似乎并没有改变,它给了我一个问题。用于休眠的Java类型转换

E.g.

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

class FooDTO extends Foo { 
... 
} 

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

在hibernate中,当保存“父”时,它仍然认为它是一个DTO对象,无法保存。我真的可以将一个子实例变成父实例吗?

回答

0

不,你不能以这种方式把孩子变成父母。你已经创建了父对象的对象,如: Foo parent new Foo(dto.getA(),dto.getB());

1

您可以使用hibernate的save(entityName, object)方法保存'父'。在这种情况下,entityName是“父”的完全限定类名。

0

对象的类型在创建后无法更改。如果您创建一个FooDTO对象,它将始终是一个FooDTO对象。

当你施放你告诉你要使用X类型的引用在您知道的对象指向的JVM是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    

    } 
}