How do I force a polymorphic call to the super met

2020-02-10 04:16发布

I have an init method that is used and overridden through out an extensive heirarchy. Each init call however extends on the work that the previous did. So naturally, I would:

@Override public void init() {
   super.init();
}

And naturally this would ensure that everything is called and instantiated. What I'm wondering is: Can I create a way to ensure that the super method was called? If all of the init's are not call, there is a break down in the obejct, so I want to throw an exception or an error if somebody forgets to call super.

TYFT ~Aedon

7条回答
做自己的国王
2楼-- · 2020-02-10 04:40

Make the class at the top of the inheritance tree set a flag on initialization. Then a class in the bottom of the inheritance tree can check for that flag to see if the whole tree has been traversed. I would make documentation that every child of base should include the following init code:

super.init()
if (!_baseIsInitialized) {
    // throw exception or do w/e you wish
}

where base uses

_baseIsInitialized = true;

The other way around, forcing your childs to call super.init() is a lot thougher and would most likely include ugly hacks.

查看更多
登录 后发表回答