Search code examples
javaconstructorinstancedeclarationrunnable

Creating a runnable that uses parameters


I am doing some Android programming and I want to create a runnable that accepts intents. I understand that the general way of creating a runnable is:

Runnable R1 = new Runnable(){ Code };

What I want is for my runnable to accept an intention as a parameter or input. The runnable then uses the intention for something else. I imagine that I would look something like this:

Runnable R1 = new Runnable(Intent i1){ Code };

I have tried this and variations of this and cannot get it to compile. How do I do this?


Solution

  • To accept parameters, a new class must be created that conforms to Runnable so that the parameters can be passed to (and used usefully in) the constructor. An alternative approach to capture state which is useful with anonymous Runnable objects is to access final variables in the lexical scope.

    With a new class and a constructor that accepts parameters and stores the values for later use:

    class RoadRunner implements Runnable {
       String acmeWidget;
       public RoadRunner (string acmeWidget) {
         this.acmeWidget = acmeWidget;
       }
       public void run () {
         evadeCleverPlan(acmeWidget);
       }
    }
    
    void doIt () {
      Runnable r = new RoadRunner("Fast Rocket");
      // do something with runnable
    }
    

    (If RoadRunner is an inner class - that is a non-static nested class - it can also access instance members of the enclosing type.)

    With an anonymous Runnable and a "poor man's closure":

    void doItAnon () {
      final String acmeWidget = "TNT";
      Runnable r = new Runnable () {
        public void run () {
          evadeCleverPlan(acmeWidget);
        }
      };
      // do something with runnable
    }
    

    (This anonymous Runnable can also access instance members of the containing type as anonymous classes are inner classes.)