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?