1

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

Bob
  • 141
  • 1
  • 8

2 Answers2

4

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).

Community
  • 1
  • 1
Simon
  • 9,255
  • 4
  • 37
  • 54
0

Instead of using this.token use OuterClass.this.token where OuterClass is the name of your class

kaysush
  • 4,797
  • 3
  • 27
  • 47
  • The variables are not fields. So this would lead also to an error. – Simon Jan 03 '13 at 14:52
  • @Simon Indeed they are instance fields that's why he mentioned to use getter methods. – kaysush Jan 03 '13 at 14:55
  • 1
    @Suhil You're right. The question is not clear about it. The code suggests that those variables are declared inside a method but at the same time he states he could use getters. If you edit your answer (add a whitespace or so), I can take back my downvote. :-) – Simon Jan 03 '13 at 15:00