2

When using an anonymous innerclass inside a method, when we want to use a method parameter inside the anonymous innerclass, we must mark it as final. Some details here: Why do we use final keyword with anonymous inner classes?

But what happens when using a class attribute and not a method local attribute?

Simple usecase: a Spring service with a Guava function:

protected LovValueDAO lovValueDAO;

private final Function<String,LovValue> LOV_ID_TO_LOV = new Function<String,LovValue>() {
    @Override
    public LovValue apply(String input) {
        return lovValueDAO.findById(input);
    }
};

@Required
public void setLovValueDAO(LovValueDAO lovValueDAO) {
    this.lovValueDAO = lovValueDAO;
}

Is it secure to declare such a Guava function? According to my tests it works fine but what happens behind the hood?

The initialization order is:

  • Function is initialized
  • lovValueDAO is injected by spring through the setter

Thus i guess, as the function is initialized first, that the lovValueDAO attribute used inside the function will not be a copy of the reference but the reference itself since once the DAO is really injected it works fine.

Am i correct?


And what happen if i use this code:

private final Function<String,LovValue> LOV_ID_TO_LOV = new Function<String,LovValue>() {
    @Override
    public LovValue apply(String input) {
        return lovValueDAO = null;
    }
};

Will my outside attribute protected LovValueDAO lovValueDAO; be set to null after i call the function?

Community
  • 1
  • 1
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419

1 Answers1

4

Inner class holds an implicit reference to this of its enclosing instance (i.e. an instance of its declaring class in context of which it was created), so that access to fields of the declaring class is treated as a normal field access by that reference.

So, your inner class will see the current value of the field, and can change it as well.

axtavt
  • 239,438
  • 41
  • 511
  • 482