如何检查功能是否已经被称为java吗? [英] How to check whether a function is already called in java?
问题描述
我呼吁在我的Android的Java项目两次的方法,但我想调用它只有一次。当我打电话一秒钟时间的方法,我想检查是否该方法已经被调用或没有。 code是这样的:
类SomeClass的{
//调用特定的条件
私人无效A(){
C(); //第一个电话
} 私人无效B(){
C(); //第二个电话,请参考以下功能是否已经或不调用,如果调用这里不能援引反之亦然
} //调用特定的条件
私人无效C(){ }
}
您必须使用一个布尔(或柜台)来记录该方法是否已被调用。但它是如何做的,你要看的 precisely 的你正在尝试数/限制。
下面假设你用一个计数器:
-
如果你想算到方法的调用在所有情况下:
私有静态诠释nos_calls; 公共无效函数c(){
nos_calls + = 1;
//做电话
} -
如果你只是想算方法的呼吁,然后给定对象:
私人诠释nos_calls; 公共无效函数c(){
nos_calls + = 1;
//做电话
} -
如果你想的 prevent 的被调用一次以上的方法:
私人诠释nos_calls; 公共无效函数c(){
如果(nos_calls ++ == 0){
//做电话
}
} -
如果该方法可以从不同的线程调用,那么你需要做的是在正确同步的方式计数;例如。
私人的AtomicInteger nos_calls =新的AtomicInteger(); 公共无效函数c(){
如果(nos_calls.incrementAndGet()== 1){
//做电话
}
} -
等。
I have called a method twice in my Android Java project but i want to invoke it only once. When I am calling the method for a second time, I want to check whether the method has already been invoked or not. Code is something like this:
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() {
}
}
You have to use a boolean (or counter) to record whether the method has been called already. But how you do it depends on precisely what you are trying to count / limit.
The following assumes that you use a counter:
If you want to count all calls to the method in all contexts:
private static int nos_calls; public void function c() { nos_calls += 1; // do the call }
If you just want to count the calls of the method for a given object then:
private int nos_calls; public void function c() { nos_calls += 1; // do the call }
If you want to prevent the method from being called more than once:
private int nos_calls; public void function c() { if (nos_calls++ == 0) { // do the call } }
If the method could be called from different threads then you need to do the counting in a way that synchronizes properly; e.g.
private AtomicInteger nos_calls = new AtomicInteger(); public void function c() { if (nos_calls.incrementAndGet() == 1) { // do the call } }
And so on.
这篇关于如何检查功能是否已经被称为java吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!