Warning developers to invoke `super. in Java foo()`

Suppose I have these two classes, one extending the other

public class Bar{

    public void foo(){

    }

}

public class FooBar extends Bar {

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

}

What I want to do is warn users to call the superclass method foo. Is this possible if they are not in the override method?

Or is there any way to know that if I pass the class type to super and use reflection to override the method of its superclass method to call the original method?

For example:

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();
    }

}

Maybe even a comment I can put on the super method, so it indicates that it needs to be called?

edit

Note that it is not a superclass that needs to call foo methods. It may be someone calling foo methods of subclasses, such as database shutdown methods

I would even be happy to make this method "non rewritable" if it boils down to it, but still want to give it a custom message

Edit 2

This is the way I want:

But it's still good to have the above content, or even give them a custom message to do other things. For example, you can't override the final method of bar. Please call it from your method implementation

Solution

Edit: answer edited questions, including:

... let the method end This will prevent subclasses from overriding it From section 8.4 3.3 of the JLS start:

To answer the original question, consider using 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() {
        // ...
    }
}

This does not force a subclass of foobar to override fooimpl and, of course, call super Fooimpl () – but foobar can do this by applying the same pattern again – finalizing its own fooimpl implementation and introducing a new protected abstract method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>