开发者

Java: How can we create callback function when "function pointer is prohibited"? [duplicate]

开发者 https://www.devze.com 2023-04-09 15:21 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What's the nearest substitute for a function pointer in Java?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What's the nearest substitute for a function pointer in Java?

Callback functions in Java

I would like to ask some concept of the term callback.

What is the main purpose of using callback? Is it only for doing some async function? from the wiki, i can't get what does actually means.

This part of code is copied from wiki- callback

    void PrintTwoNumbers(int (*numberSource)(void)) {
        printf("%d and %d\n", numberSource(), numberSource());
    }

    /* One possible callback. */
    int overNineThousand(void) {
        return (rand() % 1000) + 9000;
    }

    /* Here we call PrintTwoNumbers() with three different callbacks. */
    int main(void) {
        P开发者_如何学GorintTwoNumbers(overNineThousand);
}

from the wiki, it said the we need to pass a function pointer as arguments to other functions in order to do a callback.

But in java, there is no way to pass-by-references when we call a function, can we make a callback function in Java just like above code?

Thanks


Up until now, Java has used interfaces and (sometimes anonymous) implementations of said interfaces to behave as callbacks.

For simple callbacks, you can use java.util.Runnable or java.util.concurrent.Callable instead of defining your own interfaces.

Upcoming versions of Java will add better support for doing elegant callbacks, see this.


You can create an anonymous class instance implemening interface with only one method e.g. Callable:

Callable<Integer> function = new Callable<Integer>() {
  Integer call() {
    return ...;
  }
}

And then in the code that uses a callback just call it like that:

int result = function.call();


Function pointers are what you use if you do not have an OO language. C++ inherited them from C. Instead, take a look at the Strategy design pattern.


not really the only thing you can pass is object references but with the right interface...

return new CallBack(){
public void call(){
   //...
}
}

generics for ret value and args will be a nice expansion

0

精彩评论

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

关注公众号