Reputation: 5329
I have the following code
public class A extends Iterable<Integer> {
...
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
A a;
public boolean hasNext() {
...
}
public Integer next() {
...
}
public void remove(){
...
}
};
I would like to initialize the "a" field in the anonymous class with the instance of A that iterator method was called on. Is it possible?
Thank you.
Upvotes: 1
Views: 3942
Reputation: 10697
Try this:
public class A extends Iterable<Integer> {
public Iterator<Integer> iterator() {
final A a = this;
return new Iterator<Integer>() {
public boolean hasNext() {
// here you can use 'a'
}
}
}
}
Upvotes: 1
Reputation: 888087
You don't need to.
You can call methods on the outer class normally within the inner class.
When you compile it, the compiler will automatically generate a hidden field that contains a reference to the outer class.
To reference this variable yourself, you can write A.this
. (A.this
is the compiler-generated field and is equivalent to your a
field)
Upvotes: 10