我在Android Java项目中两次调用了一个方法,但是我只想调用一次。当我第二次调用该方法时,我想检查该方法是否已经被调用。代码是这样的:
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() {
}
}
Run Code Online (Sandbox Code Playgroud)
您必须使用布尔值(或计数器)来记录该方法是否已被调用。但如何你做这取决于正是您要计数/限制什么。
以下假设您使用计数器:
如果要在所有上下文中计算对该方法的所有调用:
private static int nos_calls;
public void function c() {
nos_calls += 1;
// do the call
}
Run Code Online (Sandbox Code Playgroud)如果只想计算给定对象的方法调用,则:
private int nos_calls;
public void function c() {
nos_calls += 1;
// do the call
}
Run Code Online (Sandbox Code Playgroud)如果要防止多次调用该方法:
private int nos_calls;
public void function c() {
if (nos_calls++ == 0) {
// do the call
}
}
Run Code Online (Sandbox Code Playgroud)如果可以从不同的线程调用该方法,则需要以正确同步的方式进行计数。例如
private AtomicInteger nos_calls = new AtomicInteger();
public void function c() {
if (nos_calls.incrementAndGet() == 1) {
// do the call
}
}
Run Code Online (Sandbox Code Playgroud)等等。
| 归档时间: |
|
| 查看次数: |
8482 次 |
| 最近记录: |