开发者

How to create an error message when a parent object is being deleted before the child object is deleted?

I am trying to create an error message in the case where a parent object has been called to be deleted but there are still child objects within that object. For example, there is a project object that contains several customer objects. I want an error message to appear if the project object 开发者_Python百科is deleted but the project still has a customer attached with it then to have an error message appear.

Is there a certain annotation that can check if any customers are present?


The parent has to care for it's children. The parent must raise the error (throw an exception, return an error code, etc.) if it still has children and can't be deleted.

Something like that:


public boolean dispose() {
  if (hasChildren())
     return false;      // not disposed/deleted

  // do disposing stuff
  isDisposed = true;    // flag the disposed state
  return true;          // disposed / deleted
}


In general, if one object has a vested interest in another object, you can use something like an Observer pattern. In this case, when the child is created, the parent can observe it.

In your case, when the parent is being destroyed (say, in its finalize() method), it can see if any children still exist and throw an error if there are.

If the parent maintains a list of children, you might simply throw an error in the parent's finalize() method if the list is not empty.

EDIT: You may have to wait for garbage collection to occur for finalize() to be called. Please see Is there a destructor for Java? for the full story.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜