警告开发人员在java中调用`super.foo()`

Fab*_*ook 7 java reflection

假设我有这两个类,一个扩展另一个类

public class Bar{

    public void foo(){

    }

}

public class FooBar extends Bar {

    @Override
    public void foo(){
        super.foo(); //<-- Line in question
    }

}
Run Code Online (Sandbox Code Playgroud)

我想要做的是警告用户调用超类的方法,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();
    }

}
Run Code Online (Sandbox Code Playgroud)

也许甚至是一个注释我可以放在super方法上,所以它表明需要调用它?


编辑

注意,它不是需要调用foo方法的超类,它可能是有人调用子类的foo方法,例如数据库close方法

我甚至会很高兴让这个方法"不可覆盖",如果它归结为它,但仍然想给它一个自定义的消息.


编辑2

这就是我想要的方式:

在此输入图像描述

但是拥有上述内容仍然很好,甚至可以给他们一个自定义消息来做其他事情,比如 Cannot override the final method from Bar, please call it from your implementation of the method instead

Jon*_*eet 4

编辑:回答编辑后的问题,其中包括:

我什至很乐意让该方法“不可重写”

...只是制定方法final。这将防止子类覆盖它。来自JLS 第 8.4.3.3 节

可以声明一个方法final来防止子类覆盖或隐藏它。

尝试覆盖或隐藏final方法是一个编译时错误。

要回答原来的问题,请考虑使用模板方法模式

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() {
        // ...
    }
} 
Run Code Online (Sandbox Code Playgroud)

当然,这不会强制 的子类FooBar重写fooImpl和调用super.fooImpl()- 但FooBar 可以通过再次应用相同的模式来做到这一点 - 使其自己的fooImpl实现成为最终的,并引入新的受保护的抽象方法。