Reputation: 141
let me say first that I did try to Google this, but I'm not really sure what I'm looking for. I understand I could use a setter method, but is there a way to access the fields directly?
List<String> token = new ArrayList<String>();
List<String> lemma = new ArrayList<String>();
List<String> pos = new ArrayList<String>();
tt.setHandler(new TokenHandler<String>() {
@Override
public void token(final String token, final String pos, final String lemma) {
this.token.add(token); // cannot be resolved or is not a field
this.lemma.add(lemma); // cannot be resolved or is not a field
this.pos.add(pos); // cannot be resolved or is not a field
}
});
Can you help me?!
Thanks!
Bob
Upvotes: 1
Views: 164
Reputation: 9365
Using the keyword this
in front of the variable, indicates that you want to access to instance fields. In this case the fields you would like to access, would belong to the anonymous class instance new TokenHandler<String>() { //... }
. Since they are not declared inside the anonymous class, the compiler is not able to resolve them. That's why you are probably getting an error.
Add the keyword final
and access to the variables without the this
-keyword:
final List<String> tokens = new ArrayList<String>();
final List<String> lemmas = new ArrayList<String>();
final List<String> positions = new ArrayList<String>();
tt.setHandler(new TokenHandler<String>() {
@Override
public void token(final String token, final String pos, final String lemma) {
tokens.add(token);
lemmas.add(lemma);
positions.add(pos);
}
});
For further information about why you need final
see this question.
EDIT:
Also, be careful with the ambigous names (parameter list vs. method variables).
Upvotes: 4
Reputation: 4836
Instead of using this.token
use OuterClass.this.token
where OuterClass
is the name of your class
Upvotes: 0