簡體   English   中英

休眠的Java類型轉換

[英]Java type casting for hibernate

是的,我知道我們可以使用Java進行上轉換或下轉換。 但是實例的類型似乎並沒有真正改變,這給我帶來了問題。

例如

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

class FooDTO extends Foo {
...
}

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

在休眠狀態下,保存“父對象”時,仍然認為它是DTO對象,無法保存。 我真的可以將子實例變成父實例嗎?

您可以使用休眠的save(entityName, object)方法保存“父級”。 在這種情況下,entityName是“ parent”的完全限定的類名。

不,您不能以這種方式將孩子割裂成父母。 您已經為父級創建了對象。例如,Foo父級new Foo(dto.getA(),dto.getB());

創建對象后,無法更改其類型。 如果創建FooDTO對象,它將始終是FooDTO對象。

強制轉換時,您告訴JVM您將使用類型X的引用來指向您知道類型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            

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM