Upcasting doesn't change the object itself, only the type of the reference that points to it. You will have to register B.class.
Java: How to force upcast?
Question
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)
?
Solution
OTHER TIPS
You can't actually do this since as you stated, casting does not change the fact that the object is still an instance of B, not A. You will need to make A delegate to a composite instance of B and pass it through the constructor as you suggested.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow