[Techtalk] Java Question

James Sutherland jas88cam at gmail.com
Wed Apr 30 14:20:07 UTC 2008


On 30 Apr 2008, at 14:38, Sue Stones wrote:

> Any Java Gurus out there?
>
> Is it possible to pass a method as argument and return type in  
> Java?  I
> was planning to do then realised I don't know how.  I have passed
> functions as arguments before, but now that I come to it realise it  
> was
> probably in C.
>
> I need to implement an interface (Runnable) where one method (run) is
> different under different circumstances.  Having a separate class  
> which
> deals with the circumstances and returns the correct run method seems
> like the neatest way of solving this, but I can't think what the  
> return
> type would be!  Googling the idea just brings lots of introductory  
> pages
> about method arguments.

You can certainly pass and return *objects* - this is almost certainly  
what
you need to do here. Something like:

public static Runnable getHandler(final boolean funny)
{
    if (funny)
    {
       return new Runnable() { public void run()  
{ System.out.println("Ha!"); }};
    }
    else
    {
       return new Runnable() { public void run()  
{ System.out.println("Not"); }};
    }
}


Now, calling getHandler(true) will give you a Runnable object where  
run()
prints "Ha!", change that to false and it prints "Not" instead.  
Alternatively,
you could move the 'if' statement inside the run() method, so you have  
one
run() method which behaves differently depending on what argument had
been passed to getHandler().


James.


More information about the Techtalk mailing list