开发者

Create method with function parameter

I've just discovered this method :

new Thread(
            new Runnable() {
                public void run() {
                    try {
                        // MY CODE
                    } catch (Except开发者_如何学运维ion 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 :)


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜