Is there a good way to find out if a method was called by a parent or from another place?

I have the following code, the purpose of which is, when the method is called for the parent, then it calls the same method for all the children, then this is where the real work was done.

public class Parent {

    Child[] children;

    public doWork() {
        for(int i = 0; i < children.size(); i++) //For all my children
            children.get(i).dowork();            //Call the same method
        Log.ReportWorkBeingDone(this);           //Report this has happened
    }
}

public class Child extends Parent{

    @override
    public doWork() {
        //Actual Work                            //Run the actual code
        Log.ReportWorkBeingDone(this);           //Report this has happened
    }
}

Right now, when doWork()called for the parent, the class Logreceives a method call from Parentand then once from each of the Childobjects in this array.

Log? , doWork() - , Log , doWork() Log ?


, , - :

public class Parent {

    Child[] children;

    public doWork() {
        sneakyHiddenWork();
        Log.ReportWorkBeingDone(this);                     //Report this has happened
    }

    protected sneakyHiddenWork(){
        for(int i = 0; i < children.size(); i++)           //For all my children
            children.get(i).sneakyHiddenWork();            //Call the same method
    }

}

public class Child extends Parent{

    @override
    protected sneakyHiddenWork() {
        //Actual Work                                      //Run the actual code
    }
}
+4
1

(sneakyHiddenWork) - ... . ( "". , .)

, , , Java 1 , , , Throwable::getStackTrace. ( , logger, log4j, ...)

. : 2


1 - " ". , , , , Throwable::getStackTrace .

2 - . Java 9 API StackWalker , - , StackWalker .

+2

Source: https://habr.com/ru/post/1690533/


All Articles