0

I have multiple methods for another class which I have to call times times.(times is always >0) I want to do this in another method doit by giving it times and then it looks where it was called from and calls for example super.move the amount of times

  @Override
  public void move(int times) {
    doit(times);
  }

  @Override
  public void turnLeft(int times) {
    doit(times);
  }
  @Override
  [...]

public void doit (int t){
  for (int r=-t; r>0; r--)
   super.getDeclaredMethod(Thread.currentThread().getStackTrace()[2].getMethodName(), RepetitiveRobotImpl);// ?????
}

"getDeclaredMethod()" https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

"Thread.currentThread().getStackTrace()[2].getMethodName()" How do I find the caller of a method using stacktrace or reflection?

1 Answers1

0

Wouldn't it be easier to use lambdas? That would require changing your doit() method to

public void doit(int t, Runnable r) {
    for (int i = 0; i < t; i++) {
        r.run();
    }
}

And you would call it like this:

public void move(int times) {
    doit(times, this::move);
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34