How to pass parameters to anonymous class?

Lewis picture Lewis · Feb 24, 2011 · Viewed 91.5k times · Source

Is it possible to pass parameters, or access external parameters to an anonymous class? For example:

int myVariable = 1;

myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // How would one access myVariable here?
    }
});

Is there any way for the listener to access myVariable or be passed myVariable without creating the listener as an actual named class?

Answer

Adam Mlodzinski picture Adam Mlodzinski · Aug 31, 2012

Yes, by adding an initializer method that returns 'this', and immediately calling that method:

int myVariable = 1;

myButton.addActionListener(new ActionListener() {
    private int anonVar;
    public void actionPerformed(ActionEvent e) {
        // How would one access myVariable here?
        // It's now here:
        System.out.println("Initialized with value: " + anonVar);
    }
    private ActionListener init(int var){
        anonVar = var;
        return this;
    }
}.init(myVariable)  );

No 'final' declaration needed.