警告开发人员在java中调用`super.foo()`
|
假设我有这两个类,一个扩展另一个类 public class Bar{
public void foo(){
}
}
public class FooBar extends Bar {
@Override
public void foo(){
super.foo(); //<-- Line in question
}
}
我想要做的是警告用户调用超类的方法foo,如果他们没有在覆盖方法中,这可能吗? 或者有没有办法知道,如果我将类类型传递给super,使用反射覆盖其超类方法的方法调用原始方法? 例如: public abstract class Bar{
public Bar(Class<? extends Bar> cls){
Object instance = getInstance();
if (!instance.getClass().equals(cls)) {
throw new EntityException("The instance given does not match the class given.");
}
//Find the method here if it has been overriden then throw an exception
//If the super method isn't being called in that method
}
public abstract Object getInstance();
public void foo(){
}
}
public class FooBar extends Bar {
public FooBar(){
super(FooBar.class);
}
@Override
public Object getInstance(){
return this;
}
@Override
public void foo(){
super.foo();
}
}
也许甚至是一个注释我可以放在super方法上,所以它表明它需要被调用? 编辑 注意,它不是需要调用foo方法的超类,它可能是有人调用子类的foo方法,例如数据库关闭方法 我甚至会很高兴让这个方法“不可重写”,如果它归结为它,但仍然想给它一个自定义的消息. 编辑2 这就是我想要的方式: 但是拥有上面的内容仍然很好,或者甚至给他们一个自定义消息来做其他事情,比如,不能覆盖Bar的最终方法,请从你的方法实现调用它 解决方法编辑:回答编辑过的问题,其中包括:
…让方法最终.这将阻止子类覆盖它.从section 8.4.3.3 of the JLS开始:
要回答原始问题,请考虑使用template method pattern: public abstract class Bar {
public foo() {
// Do unconditional things...
...
// Now subclass-specific things
fooImpl();
}
protected void fooImpl();
}
public class FooBar extends Bar {
@Override protected void fooImpl() {
// ...
}
}
这并不强制FooBar的子类覆盖fooImpl并且当然调用super.fooImpl() – 但是FooBar可以通过再次应用相同的模式来做到这一点 – 使自己的fooImpl实现最终,并引入一个新的受保护的抽象方法. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
