Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scope of a variable

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

public void myMethod(int myInteger) {
    View.OnClickListener myClearHandler = new View.OnClickListener() {
        public void onClick(View v) {
            //***How can I get the value of "myInteger" here?***
        }
    };
}
like image 342
Gohary Avatar asked Sep 11 '26 08:09

Gohary


1 Answers

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.

like image 164
Jon Skeet Avatar answered Sep 13 '26 21:09

Jon Skeet