Is there a way in java to do开发者_如何学Go something like this:
void fnc(void Reference_to_other_func());
What I'm trying is basically I have number of places where I need to display this same text to the user and the only difference is which method is invoked after this text. So for example instead of writing:
System.out.println("Hello");
f1();
//in some other place
System.out.println("Hello");
f2();
//etc
I would like to define one function:
public void f(void Reference_to_other_func())
{
System.out.println("Hello");
Reference_to_other_func();//HERE I'M INVOKING
}
and then instead of repeating this whole code I could write something like this:
f(f1);
//in some other place
f(f2)
//etc.
Thanks for answers
Java does not have first-class functions, which makes most functional-programming techniques somewhat tedious to implement.
In this case, you can make an interface:
public interface Callback {
void doCallback();
}
(Edit: or you could use java.util.concurrent.Callable<V>
, which allows you to specify a return type)
then declare f
to take an instance of this interface:
public void f(Callback callback) {
System.out.println("Hello");
callback.doCallback();
}
and pass an instance of this interface to the function:
f(new Callback() {
public void doCallback() {
f1();
}
});
f(new Callback() {
public void doCallback() {
f2();
}
});
As you can see, the gains are not going to become apparent unless you're doing this quite a lot.
By Reflection you could get the actual Method object and then do.
public void f(Method m) { System.out.println("Hello"); m.invoke(this, null); }
Unfortunately (IMHO) methods (functions) are not first-class objects in java, meaning that you can't create anonymous or named methods, without attaching it to a class first.
You could implement a class that only do one thing (for instance, like Callable or Runnable does)
You can create a anonymous class like this:
Runnable x = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
}
}; //<-- notice the semi-colon.
and you can define your function f like this:
public void f( Runnable x ) {
System.out.println("Hello");
x.run();
}
}
And call it like this.
...
// call the f-function :-)
f( new Runnable(){
@Override
public void run() {
System.out.println("World!");
}
}});
精彩评论