【问题标题】:call methods multiple times with Thread.currentThread().getStackTrace()使用 Thread.currentThread().getStackTrace() 多次调用方法
【发布时间】:2021-11-24 12:09:11
【问题描述】:

我有多个方法用于另一个类,我必须调用 times 次。(时间总是 >0) 我想在另一种方法doit 中执行此操作,方法是给它times,然后它会查看调用它的位置并调用例如super.move 的次数

  @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?

【问题讨论】:

    标签: java methods stack-trace super


    【解决方案1】:

    使用 lambdas 不是更容易吗?这需要将您的 doit() 方法更改为

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

    你会这样称呼它:

    public void move(int times) {
        doit(times, this::move);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多