Java method extension instead of overwriting - java

Is there some type of #annotation, or other method, in Java to enforce method extension, instead of overriding?
To be specific, let's say I have a class Foo:
class Foo {
public void bar(Thing thing) {
// ...
}
}
Is there a way I can enforce, at compile time, that any class X that extends Foo, and also overrides bar, makes a call to super.bar(thing) first?

No, you have to explicitly write it.
Side note for constructors: the superclass' nullary constructor will be implicitly called when instantiating the subclass, however many parameters the latter's constructor has.

You could declare bar to be final, then call an abstract method from bar, which would force subclasses to implement an "extension".
abstract class Foo {
public final void bar(Thing thing) {
barImpl(thing);
overrideMe(thing);
}
private final void barImpl(Thing thing) {
// Original implementation of "bar" here.
}
protected abstract void overrideMe(Thing thing);
}
EDIT
I've changedoverrideMe from public to protected so users of Foo can't just call overrideMe instead of bar.

Generally, what you can do is to create a final method, that calls the extendable one.
class Foo {
#Override
public final void bar(Thing thing) {
// super code comes here
this.doBar(thing);
}
public abstract void doBar(Thing thing);
}
When you call
foo.bar(thing);
your super code runs first, then the code from the child class.
This way you can protect your full bar logic, and allow only certain parts to be extended/reimplemented.
Also, it allows you to postprocess the result, or to break up your code to certain subtasks.

While you cannot force code to call up to its superclass at compile time, it's not too hard to detect at run time when code does not call up to the superclass.
class Foo {
private boolean baseCalled;
public final void bar(Thing thing) {
baseCalled = false;
barImp(thing);
if (!baseCalled) {
throw new RuntimeException("super.barImp() not called");
}
}
protected void barImp(Thing thing) {
baseCalled = true;
. . . // base class implementation of bar
}
}
Note that this extends to multiple levels of inheritance without further elaboration. The method works particularly well for methods that are called from within Foo; in those cases, you can often forgo the final qualifier and redirection to an implementation method, and just define the base class method to set the flag. Clearing the flag would be done at each point of invocation.
The above pattern is used extensively in the Android framework. It doesn't guarantee that super.barImp was called as the first thing in subclass overrides; just that it was called.

You can try to use #AroundInvoke annotation, if you are using EJBs.
By using reflection, you can find the same method in your parent class, and yo can invoke it with the same parameters as the original method was called.
Note, that in this case you must avoid super.bar(thing) calls, otherwise they would be called twice.

Related

Enforce super call on non constructor methods

Is it possible to enforce an overriden method to call the superclass method? Constructors always need to call their superclass constructor. But i want to enforce this on normal methods, without the position of when it is called mattering.
Example:
public class A {
public void doSth() {
System.out.println("I must appear on console!");
}
}
public class B extends A {
#Override
public void doSth() {
System.out.println("Bla!"); // IDE should mark an error, because supermethod is not called.
}
}
No, that is not possible. It is entirely up to the overriding method to call the superclass method, or not.
However, there is a way to do it, if you want to enforce control.
This is called the Template Method Pattern. Whether the template methods are abstract or stubs (like shown here), depends on whether they must do something, or simply allow something extra to be done.
public class A {
public final void doSth() { // final, preventing override by subclasses
beforeDoSth();
System.out.println("I must appear on console!");
afterDoSth();
}
protected void beforeDoSth() { // protected, since it should never be called directly
// Stub method, to be overridden by subclasses, if needed
}
protected void afterDoSth() {
// Stub method, to be overridden by subclasses, if needed
}
}
public class B extends A {
#Override
protected void afterDoSth() {
System.out.println("Bla!");
}
}
If you then execute new B().doSth(), you'll get:
I must appear on console!
Bla!
No, it is not possible. If you allow a method to be overridden at all (by not declaring it or its class final) then you cannot control much of anything about the implementation of methods that override it. You can, however, document that such methods should invoke the superclass's version. There's only so much you can do to protect your users from themselves.
You may also find that there are alternative designs that would suit you better. For example, if you want to allow subclasses to override particular details of a computation, but not to override the whole computation altogether, then you could employ the Template Method pattern. In that case, the computation is driven by one "template" method, which you can declare private or final if you wish, and the customizable details are implemented in a separate, non-final, public or protected, possibly abstract method that the driver method calls where appropriate.
Although not strictly Java related, I was looking for an answer to this issue as it relates to Android and found the annotation in the support annotations library called "#CallSuper". It does exactly what you think, and throws a lint error if the subclass does not call the super's implementation of methods annotated with #CallSuper.
That solved my usecase, but again, I know that the solution is strictly tied with Android. Please let me know if that is too far off base and I will remove the answer.
Here is some more documentation on #CallSuper.
https://developer.android.com/reference/android/support/annotation/CallSuper.html
https://developer.android.com/studio/write/annotations.html (just search for CallSuper and it'll show right up in that second link.
No, it is not possible. It is up to the overriding method to call or to not call the method that it overrides.
Yes, it's possible, given the following constraints:
The method has a non-void return type
Subclasses (or other classes accessible by the subclasses) cannot create instances of the return type
As #Andreas pointed out, the super call could still be avoided by returning null. In practice, this shouldn't be a problem, but it's reasonable to enforce non-nullness in the contract (super class documentation) and also by using a null-preventing annotation, e.g. #Nonnull, so that any modern IDE can give a compile error when the super class method is not called.
For example:
import javax.annotation.Nonnull;
public class A {
public static final class Result {
private Result() {
// declare constructor private so the class cannot be
// instantiated from outside
}
}
/**
* Does something.
*
* #return the result; never {#code null}
*/
public #Nonnull Result doSth() {
System.out.println("I must appear on console!");
return new Result();
}
}
//...
public class B extends A {
#Override
public #Nonnull Result doSth() {
System.out.println("Bla!");
// only way to get a Result instance is through super.doSth()
Result res = super.doSth();
/* manipulate the result as needed */
return res;
}
}

Can I tell if an abstract method has been called?

Given this class:
abstract class Foo{
public Foo(){...}
public abstract void checkable();
public void calledWhenCheckableIsCalled(){
System.out.println("checkable was called");
}
}
Is there any code I can put in Foo's constructor to make calledWhenCheckableIsCalled get called when checkable is called?
Note: This is a gross simplification of an actual project I am working on.
Edit: I have already implemented a template pattern workaround. I just wondered if there was another way to do this I am missing. (Perhaps using reflection.)
Looks like a template method pattern.
But then you must implement Foo.checkable() and introduce another abstract method to delegate to.
abstract class Foo{
public Foo(){}
public void checkable(){
calledWhenCheckableIsCalled();
doCheckable();
}
protected abstract void doCheckable();
public void calledWhenCheckableIsCalled(){
System.out.println("checkable was called");
}
}
I would also suggest to make checkable() final in this case so that you can be sure that checkable() can not implemented in another way as you expected.
In addition to Brian Roach's comment
The downside is that the protected can be expanded to public in the subclass, so you can't explicitly enforce it.
That's true, but you can prevent a Foo instance from being instantiated if a subclass increases the visibility of doCheckable. Therefore you have to introduce a verification whenever an object is instantiated. I would recommend to use an initializer code so that the verification is executed on every constructor that exists. Then it can not be forgotten to invoke and therefore be by-passed.
For example:
abstract class Foo {
{ // instance initializer code ensures that enforceDoCheckableVisibility
// is invoked for every constructor
enforceDoCheckableVisibility();
}
public Foo() {...}
public Foo(Object o) {...}
private void enforceDoCheckableVisibility() {
Class<?> currentClass = getClass();
while (currentClass != Foo.class) {
try {
Method doCheckableMethod = currentClass.getDeclaredMethod("doCheckable");
if (Modifier.isPublic(doCheckableMethod.getModifiers())) {
throw new RuntimeException("Visibility of "
+ currentClass.getSimpleName()
+ ".doCheckable() must not be public");
}
} catch (SecurityException | NoSuchMethodException e) {}
currentClass = currentClass.getSuperclass();
}
}
}
Since the check is implemented using reflection the downside is that it is only checked at runtime. So you will not have compiler support of course. But this approach let you enforce that an instance of a Foo can only exist if it fulfills your contract.
No, the constructor will get invoked once during the object initialisation. You can however get your subclass that provides the implementation to call the method in the super class:
class Bar extends Foo {
// implementation of abstract method
public void checkable(){
super.calledWhenCheckableIsCalled(); // call to parent's method
...
}
}
EDIT
You could achieve this with aspects. Using an aspect you can intercept each call to a method by referring to the abstract parent method. This leaves you free from interfering eith the child code. Your calledWhenCheckableIsCalled code would then become part of the intercepting code.
abstract class Foo {
// use pointcut to intercept here
public void checkable();
}
There is no way as you are forcing that method to implement in child.
An awkward suggestion will be know from child implementation. I mean there is no clean way AFAIK
abstract class foo {
public abstract void bar();
public void moo() {
System.out.println("some code");
this.bar();
System.out.println("more code");
}
}
now if moo is called, the underlying implementation of bar will be used, it is just a small paradigm shift from what you want.
so your end user would call moo instead of bar, but he still needs to implement bar
Nope, an abstract method doesn't have a body. You could, however, chain your method like this:
abstract class Foo {
void callMeInstead() {
// do common
callMeImplementation();
}
abstract void callMeImplementation();
}
It looks to me like you're looking for the template pattern:
public abstract class Template {
public final void checkable() {
calledWhenCheckableIsCalled();
doCheckable();
}
protected abstract void doCheckable();
private void calledWhenCheckableIsCalled() {
System.out.println("checkable was called");
}
}
Now, each time checkable() is called, calledWhenCheckableIsCalled() is also called. And the suclass must still provide the actual implementation of checkable(), by implementing the doCheckable() method.
Note that making checkable() final prevents a subclass from overriding it and thus bypassing the call to calledWhenCheckableIsCalled().

Keep visibility of abstract method in subclass

I have following abstract class:
public abstract class AbstractCreateActionHandler {
protected IWorkItem mCurrentWI;
public AbstractCreateActionHandler(IWorkItem wi) {
this.mCurrentWI = wi;
}
public final void invoke() {
try {
if (checkForLockingFile()) {
this.executeAction();
Configuration.deleteInstance();
}
} catch (IOException e) {
Configuration.deleteInstance();
e.printStackTrace();
}
}
protected abstract void executeAction();
private boolean checkForLockingFile() throws IOException {
String path = Configuration.getInstance().getProperty("path");
File lock = new File(path + "lock_"+mCurrentWI.getId()+"__.tmp");
if(!lock.exists()) {
lock.createNewFile();
return true;
}
return false;
}
}
A sub class extends the abstract class:
public class MyAction extends AbstractCreateActionHandler {
public MyAction(IWorkItem wi) {
super(wi);
}
#Override
protected void executeAction() {
// Implementation
}
// ALSO POSSIBLE...
/* #Override
public void executeAction() {
// Implementation
}*/
}
Question:
Is it possible that a developer which extends the abstract class and implements executeAction() method is not allowed the change the visibilty of executeAction()?
At the moment a developer can simply change the visibilty of the method to "public", create an object of the subclass and invoke executeExtion(). The visibility modifier can be changed and the abstract method is still accepted as "implemented".
So the "normal" calling sequence and checks which are executed in abstract class method invoke() can be bypassed. Is there a way to check if the invoke() method was called?
No, there's not really a way to restrict that. are you worried about malicious developers or clueless coworkers? if the latter then you just need to establish coding conventions like "don't increase the visibility of methods" and put some javadoc on the abstract method indicating proper usage. if the former, then you probably need to design your code differently (possibly using the strategy pattern).
Is it possible that a developer which extends the abstract class and implements executeAction() method is not allowed the change the visibilty of executeAction()?
No, this is not possible.
Chapter 8.4.8.3. Requirements in Overriding and Hiding of the Java Language Specification specifies:
The access modifier (ยง6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows: ...
So it is always possible to have the overriding method provide more access than the overridden method in the parent class.
See also java access modifiers and overriding methods.
It is allowed to change the modifier to public because it does not violate the Liskov Substitution Principle.
So the "normal" calling sequence and checks which are executed in
abstract class method invoke() can be bypassed. Is there a way to
check if the invoke() method was called?
If you pass someone the reference to AbstractCreateActionHandler then the caller will not be able to see the method executeAction as it is not public in AbstractCreateActionHandler class. So the caller will not be able to bypass execution sequence if you pass reference to Base class to caller. If you pass reference to Concrete class then the sequence can be broken.

Good method to make it obvious that an overriden method should call super?

This problem just bit me, its pretty easy to forget to call super() when overriding a method.
In my case I was refactoring some existing stuff where there were already about ten classes overriding a method. Until yesterday the method had an empty default implementation, so it didn't matter if subclasses called super or not.
You can find the overriders just fine with any IDE worth its salt, but you know how it is, phone rings, colleagues have a smalltalk behind you back... its easy to forget to check a place or otherwise overlook it.
Ideally there would be a counterpart for the #Override annotation and the compiler would generate a warning for those places if the base class method is annotated but the override doesnt call super.
Whats the next best thing I can do?
Not quite elegant, but possible solution is to break that method into two:
public abstract class Foo {
public void doBar() {
// do your super logic
doBarInternal();
}
public abstract void doBarInternal();
}
If the superclass implementation MUST ALWAYS be called you could use the 'template method' pattern.
So what you have now is something like:
public static class Parent {
public void doSomething() {
System.out.println("Parent doing something");
}
}
public static class Child extends Parent {
public void doSomething() {
// MUST NOT FORGET SUPER CALL
super.doSomething();
System.out.println("Child doing something");
}
}
public static void main(String[] args) {
Child child = new Child();
child.doSomething();
}
And this would become:
public abstract static class Parent {
public final void doSomething() {
System.out.println("Parent doing something");
childDoSomething();
}
public abstract void childDoSomething();
}
public static class Child extends Parent {
public void childDoSomething() {
System.out.println("Child doing something");
}
}
public static void main(String[] args) {
Child child = new Child();
child.doSomething();
}
(classes are made static for easy testing within one class)
I made doSomething final to avoid it being overridden since in this solution childDoSomething should be implemented instead.
Of course this solution means Parent can no longer be used as a concrete class.
EDIT: after reading comments about Child implementing a third party interface; this does not need to be a problem:
public interface ThirdPartyInterface {
public void doSomething();
}
public abstract static class Parent {
public final void doSomething() {
System.out.println("Parent doing something");
childDoSomething();
}
public abstract void childDoSomething();
}
public static class Child extends Parent implements ThirdPartyInterface{
public void childDoSomething() {
System.out.println("Child doing something");
}
// public final void doSomething() {
// // cannot do this because Parent makes it final
// }
}
public static void main(String[] args) {
Child child = new Child();
child.doSomething();
}
Loooking for something else I found interesting OverrideMustInvoke annotation in FindBugs:
http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/OverrideMustInvoke.html
If you do not insist on compile time safety you could use a mechanism that throws an exception whenever a subclass does not behave as logically required: How do I force a polymorphic call to the super method?
I have 2 different suggestions:
1) Build a junit test that discovers all subclasses of your base class, and then selects all the methods decorated with the #Override annotations. I have some unit tests that do something similar (i.e. find all subclasses, check that they truly are Serializable for example).
Unfortunately, the verification of whether they call "super" is a little less straightforward. You would either need to have the test look up the source file, and search it, or better (but I don't know how to do this), read the byte code and see if you can detect the call to super.
2) Needing to guarantee a call to super is probably an indicator of a design/interface issue, rather than a coding/implementation issue. If you really want to guarantee that users call super, it would be better to make the super class abstract, clearly designate an abstract implementation method for them to override, and have the super control the flow of execution.
If you want to define a default implementation, so that not all users need to subclass provide implement that method, you could define a default implementation class for people to use. (And if you really want to control it, define that default class implementation method as final to force them to go back to subclassing the abstract parent.)
Code reuse inheritance is always harder to manage, and so it needs to be done carefully. Anyone doing code reuse inheritance has to have a good idea of the internals of the super class to do it right (which is a bit yucky). For example, do you have to call super.method() at the beginning of your overriding code, or at the end? (or could you do it in the middle...)
So in summary, the best solution is to try avoid a design where you have to enforce that.
What could work - creating some marker annotation (i.e. #MustCallParent) and then create some annotation processor to check that methods marked with it comply to the constraint.

Java Reflect/AOP override supertype private Method

Is it at all possible to "override" a private method of a super class in Java?
The class whose method I wish to override is a third party class so I cannot modify the source. It would be ideal if there were some way to reflectively set a method on a class.
Alternatively, if it is possible to intercept a private method of a third party class then this would be suitable.
YES. You can do it with AspectJ. It is not a true override but result will be so.
Here your super class;
public class MySuperClass {
private void content(String text) {
System.out.print("I'm super " + text);
}
public void echo() {
content("!");
}
}
Create an interface which contains similar method;
public interface Content {
void safeContent(String text);
}
Create an aspect that forces super class to implement that interface and add an around adviser to call it.
public privileged aspect SuperClassAspect {
void around(MySuperClass obj)
: execution(* content(String)) && target(obj) {
Object[] args = thisJoinPoint.getArgs();
((Content) obj).safeContent((String) args[0]);
}
// compiler requires
public void MySuperClass.safeContent(String text) {}
declare parents :MySuperClass implements Content;
}
Create your child class that extends super and implements that interface.
public class Overrider extends MySuperClass implements Content {
public void safeContent(String text) {
System.out.print("Not that super " + text);
}
}
Now if you construct a Overrider object and invoke echo method, you will have an output of Overriders safeContent's method.
Is it at all possible to "override" a private method of a super class in Java?
No
I don't think using Reflection there would be a tweak , it will break OOP there
You do not have a legal way to do this. But I can suggest you the following solutions.
Do you really wish to override this method? Try to think about other solution.
Java checks access permissions during compilation only. Are you surprised? I was surprised very much to find out this fact. So you can create skeleton of the third party class (even with empty implementations.). The interesting method should be protected instead of private. Now write your subclass and compile it against your stub. Then package only your subclass and try to run it with the "real" class. It should work. I have not tried this trick with inheritance but I have tried it when I had to access private method or field and it worked fine for me.
Try to use dynamic proxy that wraps your class and changes its implementation. I do not know what are you doing exactly, so I am not sure you can really use this method. But I hope you can. If not go back to #1 or #2.
yes it's possible ,but you should not do it, because it contradicts one of the SOLID principles. More exactly it contradicts Liskov substitution principle.
Note:
Let q(x) be a property provable about objects x of type T. Then q(y)
should be provable for objects y of type S, where S is a subtype of T.
So in other words , private method is property of object, so your object of inherited type must have the same property. The same with throws for methods.
Java restricts it because of it.

Categories

Resources