문제

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top