Tzu ng
Tzu ng

Reputation: 9234

Create method with function parameter

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 :)

Upvotes: 2

Views: 188

Answers (3)

Vijay Mathew
Vijay Mathew

Reputation: 27164

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.

Upvotes: 1

Nrj
Nrj

Reputation: 6831

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.

Upvotes: 2

Roman
Roman

Reputation: 66156

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
   }
});

Upvotes: 4

Related Questions