I have a code which I believe is callback
implementation. Can you please provide your more experienced opinions on whether this is a good way to callback
?
public interface Callback {
void run();
}
Test of callback
with anonymous function
public class Test {
static void method (Callback callback){
callback.run();
}
public static void main(String[] args) {
method(new Callback() {
@Override
public void run() {
System.out.println("Printed!");
}
});
}
}
-
2\$\begingroup\$ Welcome to Code Review! After having received answers, please do not add revised versions of your code to your question or modify your previous code in such a way that it invalidates answers. See our meta question Can I edit my own question to include revised code? for what you can do after having received answers to your question. \$\endgroup\$Simon Forsberg– Simon Forsberg2014年09月06日 12:19:33 +00:00Commented Sep 6, 2014 at 12:19
1 Answer 1
Yes, that is an implementation of a callback. There are some things to note though:
Callbacks in Java are seldom called Callbacks, but rather 'events' or 'listeners' (which is why you probably found it hard to search for the concepts in Java). The most common Listeners are likely in the AWT/Swing library, like ActionListener
having a
run()
method on the callback is a poor choice of name, because it confuses it with theRunnable
interface (which, in a sense, is a callback of sorts too).Java8 introduces functional interfaces which allows you to extend your callback in more concise ways. You should consider it.
Using a functional interface:
If you were to use your interface, but declare it as a functional interface to make it obvious (it is not required to declare it as functional, the compiler can automatically detect it...):
@FunctionalInterface
public interface Callback {
void run();
}
Then, in your code, you can have:
static void method (Callback callback){
callback.run();
}
public static void main(String[] args) {
method(() -> System.out.println("Printed!"));
}
(you can also use the anonymous class, but the functional-interface implementation is.... neater.
-
\$\begingroup\$ Ok. I see. Thanks. By the way I updated my question. I think now it's much more significant. \$\endgroup\$Alex– Alex2014年09月06日 12:09:44 +00:00Commented Sep 6, 2014 at 12:09
-
\$\begingroup\$ We need
callbacks
mostly for handling stuff, right? \$\endgroup\$Alex– Alex2014年09月06日 12:10:52 +00:00Commented Sep 6, 2014 at 12:10