tags:

views:

120

answers:

2

Hello,

normally I implement my Runnables as follows (directly implemented inner class):

Runnable updateRunnable = new Runnable() {

    public void run() { 
    }
}

Is there any working way in Java to implement the Class by passing any parameters in the constructor as follows?

Runnable updateRunnable = new Runnable(locale) {

    Locale locale = null;

    public Runnable(Locale locale){
        this.locale = locale
    }

    public void run() { 
    }
};

==>My goal is to have an directly implemented inner class but I want to pass in a parameter.

Whats the best solution to do this (the example above seems to not be working????) Is the only possibility to work with getter setters or alternatively implement the class as an "normal" inner class (that is not direclty implemented).

thank you very much! jan

+4  A: 

You can do something similar:

final Locale locale;
Runnable r = new Runnable() {
    public void run() {
        // have direct access to variable 'locale'
    }
};

The important thing to note is that the Locale you pass in must be final in order for you to be able to do this.

You have to initialize locale somehow for this to compile.

jjnguy
hello jjnguy, thank you very much for your helpfull solution! jan
jan
Yeah! No problem. Glad to help.
jjnguy
There's actually no need to use a local field for this. You can access the `locale` variable directly from the `run` method. If my memory doesn't fail me, it will then become an implicit field in the `Runnable` object, added by the compiler.
gustafc
Thanks for the clarification!
jjnguy
+1  A: 

The other option is to use a static inner class.

public class MyClass {

    public void someMethod() {
         Runnable runnable = new MyRunnable(someLocaleHere);
    }

    private static class MyRunnable implements Runnable {
         Locale locale = null;

         private MyRunnable(Locale locale) {
             this.locale = locale;
         }

         public void run() {
         }
    }
}

Depending on how you view things the downside of this approach is that the MyRunnable can't access final local variable like the other technique described here.

Richard Perfect