2

I've just discovered this method :

new Thread(
            new Runnable() {
                public void run() {
                    try {
                        // MY CODE
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

I wonder if I can create a method with the parameter is the function I will put to // MY CODE. Can I do that ? and how :)

3 Answers 3

4

Java doesn't support 1st-class functions (i.e. functions which can be passed as parameters or returned from methods).

But you can use some variation of Strategy pattern instead: create some interface Executable with method execute, and pass it's anonymous implementation as a parameter:

interface Executable {

   void execute();
}

...
void someMethod(final Executable ex) {
//here's your code 
       new Thread(
            new Runnable() {
                public void run() {
                    try {
                        ex.execute(); // <----here we use passed 'function'
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
       }).start();
}

...

//here we call it:

someMethod(new Executable() {
   public void execute() {
       System.out.println("hello"); // MY CODE section goes here
   }
});
Sign up to request clarification or add additional context in comments.

2 Comments

does C# support this ? Sorry for out topic question but I want to know it :)
@nXqd: in bigger extent than Java. C# has delegats, which are kind of 1st-class citizens. You'd better ask it separately and people familiar with C# provide you a good answer.
2

This is actually creating an anonymous class object (which implements the Runnable interface). So effectively you are passing the class object only. This is just sort of shorthand notation.

This is specially useful for cases where you are not going to reuse / reference the object you are creating again inside the calling code.

Now for your question - You can create a function which expects an object and while calling you can pass the required object / anonymous class object as described above.

Comments

1

Higher-level languages like Common Lisp and Python have first-class functions, which is what you are looking for. Java do not have this feature. Instead you have to use interfaces. C and C++ allows passing function pointers as arguments. C++ also have function objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.