2010-08-26 88 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    

    } 
}