hibernate的Java类型转换
是的,我知道我们可以在Java中向上或向下转换。但实例的类型似乎并没有真正改变,这给了我一个问题 例如hibernate的Java类型转换,java,hibernate,Java,Hibernate,是的,我知道我们可以在Java中向上或向下转换。但实例的类型似乎并没有真正改变,这给了我一个问题 例如 在hibernate中,保存“父对象”时,仍然会认为它是DTO对象,无法保存。我真的可以将子实例转换为父实例吗?不,你不能用这种方式将子实例转换为父实例。您已经为父对象创建了特定的对象。例如, Foo父对象新Foo(dto.getA(),dto.getB()) 您可以使用hibernate的save(entityName,object)方法保存“父对象”。在这种情况下,entityName是“
在hibernate中,保存“父对象”时,仍然会认为它是DTO对象,无法保存。我真的可以将子实例转换为父实例吗?不,你不能用这种方式将子实例转换为父实例。您已经为父对象创建了特定的对象。例如,
Foo父对象新Foo(dto.getA(),dto.getB()) 您可以使用hibernate的
save(entityName,object)
方法保存“父对象”。在这种情况下,entityName是“父级”的完全限定类名。对象的类型在创建后无法更改。如果创建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
}
}
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
}
}