I'm using the Kryo library for serialization in Java. I have a problem where I have no way to force an upcast. Here is an example situation:
class A {}
class B extends A {}
public save() {
Kryo kryo = new Kryo();
kryo.setRegistrationRequired(true); //force registration
kryo.register(A.class); //register A with kryo
Output output = new Output( ... );
B bar = new B();
kryo.writeObject(output, (A) bar); //try to cast it up
}
This causes an class not registered
error, because bar
is still an instance of B
.
Is there any way to force bar
to be cast up to an instance of A
, or will I need to do something like new A(bar)
?
Upcasting doesn't change the object itself, only the type of the reference that points to it. You will have to register B.class.