开发者

scope of a variable

How can I get the value of a method parameter "myInteger" in this code.

public void my开发者_Python百科Method(int myInteger) {
    View.OnClickListener myClearHandler = new View.OnClickListener() {
        public void onClick(View v) {
            //***How can I get the value of "myInteger" here?***
        }
    };
}


Assuming you're just trying to read it, you just need to make it final:

public void myMethod(final int myInteger) {
    View.OnClickListener myClearHandler = new View.OnClickListener() {
        public void onClick(View v) {
            int foo = myInteger;
        }
    };
}

In Java, only final parameters and local variables can be accessed within anonymous inner classes.


I am guessing the language should support closures and all you need to do in this case is use the variable myInteger in your onClick listener and you should be fine.. This works in fine in many languages I am not sure about Java though.

public void myMethod(final int myInteger) {
    View.OnClickListener myClearHandler = new View.OnClickListener() {
        public void onClick(View v) {
          int myInteger = myInteger * 100;
        }
    };
}

AS posted by John Skeet: the final keyword is important here.


You Cannot refer to a non-final variable myInteger inside an inner class 
defined in a different method

You might be getting this error, so for that you have to declare it as final like this

final int myInteger
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜