Reputation: 97
I'm going to use Hibernate for a persist some entities.
EntityClass entity = new EntityClass();
Object obj = (Object) entity;
hibernateSession.persist(obj)
Can I ensure that the field value in the original EntityClass will be preserved?
Does the garbage collector not clear field values?
In all other cases, can I ensure that the upcasting preserves the value of the original field?
(other common cases that don't use hibernate)
It is my original code
Class<?> clazz = Class.forName(~~~); // from external file
Iterator<?> iterator = ((Iterator<?>) clazz.getConstructor(String.class).newInstance(~~~); // from external file
while (iterator.hasNext()) {
for (JsonEntity content : (List<JsonEntity>) iterator.next()) {
session.saveOrUpdate(content.toEntity());
}
session.flush();
}
transaction.commit();
Upvotes: 1
Views: 219
Reputation: 611
upcasting a reference type (such as Entity) does not alter the object or it's fields. You can read more here : https://www.baeldung.com/java-type-casting
Neither does it require you to explicitly cast it since the compiler implicitly recognizes that Entity is a subclass of Object. You can simply do:
Object obj = entity;
Upvotes: 0
Reputation: 344
EntityClass entity = new EntityClass();
hibernateSession.persist(entity);
as long as your entity class is being referred, will it not be garbage collection
casting your object to a super class will not delete the original fields/methods but you can only access fields/methods which are available in super class only
Upvotes: 1