开发者

Change object type at runtime

I have the following scenario:

class Parent {}

class Child1 extends Parent {}

class Child2 extends Parent {}

interface ExternalSystem {
    Parent materialize(Parent a)
}

class Child1System implements ExternalSystem {
    Parent materialize(Parent a) {
        // specialize a and convert it into Child1
    }
}

class Child2System implements ExternalSystem {
    Parent materialize(Parent a) {
       //  specialize a and convert it into Child2
    }
}

I want to let users create objects of type Parent. Some components of the system are OK with the information that Parent provides. At some point though, I want to materialize these objects in an external system and depending on which ExternalSystem implementation I call, Parent objects should now be specialized objects.

Is there a way of creating a new child object and replace the space used by the parent object?

I can't just replace Parent a object with a new object of type Child1 or Child1 because a could have been referenced in other places. So, essentially, what I want is al开发者_如何学运维l references to keep looking at Parent a but instead of a being of type Parent it will now be of a child type.

Alternatively, can this be designed differently?


There is no placement new feature in Java. By definition of managed heap.

The only thing that you can do is to create proxy object that implements ExternalSystem. That proxy will dispatch calls to instances of child1 or child2.


Is there a way of creating a new child object and replace the space used by the parent object?

There is no way. The type of an object does not change for the lifetime of an object. A given reference always points to the same object.

You can do is to use some kind of proxying or delegation mechanism, and have the proxy / delegate refer to different things during its lifetime. The proxy / delegate object's type won't change, but it will behave like an instance of one of the child types ... in most respects. (One thing that won't work ... of course ... will be the instanceof operator.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜