Identification of caller method and arguments without reflection

Say I have a class with a method like below

public class Parent {

    public boolean isValidURL() {
        System.out.println("print the name of the caller method and the method arguements here");
        //pls ignore the return true below. just an eg.
        return true;
    }
}

Then I have another method that calls isValidURL in the parent class

public class Child {
    Parent parent = new Parent();

    public void verifyURL(String url) {
        parent.isValidURL();
    }
}

Now in the class, the Parentmethod isValidURL()should print the method of the caller, which verifyURL()and its arguments.

Is this possible without reflection? Are there any design patterns that need to be followed?

EDIT: I want to do this because I want to implement the idea in a magazine. In principle, there are many other methods, such as a method verifyURL()that takes different parameters. I would like to have a general log to print it to the console when any methods are called in the "Child" class

+4
source share
4

?

. ( , .)

- , ?

.: -)

Child Parent URL- Child.

Parent parent = new Parent(this);  // ...then look up URL through field in Child

isValidURL:

public void verifyURL(String url) {
    parent.setUrl(url);
    parent.isValidURL();
}

:

EDIT: , . , , verifyURL(), . , , - "Child"

.

. :

, , , . Parent isValidURL , , , ( Child). , , "", /:

public boolean isValidURL() {
    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
        if (ste.getClassName().equals(Thread.class.getName())
                || ste.getClassName().equals(getClass().getName()))
            continue;
        System.out.println(ste.getClassName() + "." + ste.getMethodName());
        break;
    }
    return true;
}
+7

, @LuiggiMendoza.

(. SO: fooobar.com/questions/19405/....)

new Throwable().getStackTrace(), , , . 0, () 1.

, , isValidURL() :

public boolean isValidURL() {
    StackTraceElement caller = new Throwable().getStackTrace()[1];
    System.out.println(caller.getClassName() + "." + caller.getMethodName());
    //pls ignore the return true below. just an eg.
    return true;
}

... ( ). , , , , , Child isValidURL(), .

+3

, . Log4J. verifyURL isValidURL.

    public class Child {
        private static final Logger log = LoggerFactory.getLogger(Child.class);
        Parent parent = new Parent();

        public void verifyURL(String url) {
            log.info("verifyURL called");
            parent.isValidURL();
        }
    }

: . AspectJ.

- : http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html

0

.

, , - .

.

public class Parent {

   public boolean isValidURL() {
      isValidURL( url );
      // do any other stuff necessary
   }

  public abstract isValidURL( String sURL );
}

isValidURL, , .

0

All Articles