2

Android Java プロジェクトでメソッドを 2 回呼び出しましたが、呼び出したいのは 1 回だけです。メソッドを 2 回目に呼び出すときに、メソッドが既に呼び出されているかどうかを確認したい。コードは次のようなものです。

class SomeClass {
    //called with certain condition
    private void a(){
         c(); //first call
    }

    private void b() {
         c(); //second call,check here whether function is invoked already or not,if invoked not invoke here or vice-versa
    }

    //called with certain condition
    private void c() {

    }
}
4

6 に答える 6

2

プログラムの実行時間全体で 1 回だけ実行する場合は、クラスの静的変数を使用します。オブジェクトごとに 1 回実行する場合は、オブジェクト メンバー変数を追加します。

class RunOnce {
     private static boolean methodAHasRunOnce = false;
     private boolean methodBHasRun = false;

     public void methodA() {
         if(RunOnce.methodAHasRunOnce) { return; }
         System.out.println("Hello from methodA!");
         RunOnce.methodAHasRunOnce = true;
     }

     public void methodB() {
        if(this.methodBHasRun) { return; }
         System.out.println("Hello from methodB!");
         this.methodBHasRun = true;
     }
}

今実行します:

RunOnce one = new RunOnce();
RunOnce two = new RunOnce();
one.methodA();  // Output: Hello from methodA!
one.methodB();  // Output: Hello from methodB!

one.methodA();  // No output
one.methodB();  // No output

two.methodA();  // No output
two.methodB();  // Output: Hello from methodB!

two.methodA();  // No output
two.methodB();  // No output
于 2013-04-28T09:25:06.070 に答える
1

次のようなことができます。

class A{
    static boolean calledBefore = false;
    public void a(){
    ....
         c();
    }
    public void b(){
    ....
         c();
    }
    public void c(){

         if(!calledBefore){
             //This will be executed if c() is not called before
             //Do magic here

             calledBefore = true;
         }
    }
}

calledBeforeクラス A の複数のインスタンスが必要で、各インスタンスを 1 回呼び出すことができる場合は、非静的にする必要がありますc()

于 2013-04-28T09:20:47.067 に答える
0

アスペクトは、この問題に対する一般的な解決策です。私は決して専門家ではありません (この例はテストされていません) が、次のようになります。

@Aspect
public class CallOnlyOnceAspect {

  @Pointcut("call(* methodThatShouldBeInvokedOnlyOnce(..))")
  void methodThatShouldBeInvokedOnlyOnce() {}

  @Around("methodThatShouldBeInvokedOnlyOnce()")
  public Object preventMultipleCalls(ProceedingJoinPoint thisJoinPoint) {
    // You need to implement this method for your particular methods/counters
    if (hasAlreadyExecuted(thisJoinPoint)) {
      return null;
      // or equivalent return value,
      // e.g. you may have cached the previous return value
    }
    Object result = thisJoinPoint.proceed();
    // Maybe cache result against thisJoinPoint
    return result;
  }

}

詳細については、次の場所を参照してください。

于 2013-04-28T09:29:23.987 に答える
0

呼び出しを追跡するために、関数で変更された関数を含むクラスに静的フィールドを追加できます (たとえば、関数を単に増加させるだけです)。

于 2013-04-28T09:22:57.847 に答える