The common way of getting something like Javascript's closures is using anonymous inner classes. It's a lot more verbose, but it lets you do pretty much the same thing.
Runnable r = new Runnable(){
public void run(){
System.out.println("Hello, world!");
}
};
r.run(); // Prints "Hello, world!"
You can even reference variables in the enclosing method, if they're final:
public static Runnable makeGreeter(final String who) {
return new Runnable() {
public void run() {
System.out.println("Hello, " + who + "!");
}
};
}
// ... elsewhere in your program...
Runnable r = makeGreeter("world");
r.run(); // "Hello, world!"
This is standard stuff which has been in Java since the beginning. Runnable
is a very handy interface which, according to the Javadocs, "should be implemented by any class whose instances are intended to be executed by a thread". Runnable
can be used for a lot more than threads, of course, and is generally used (in the JVM and elsewhere) as "something that can be executed" - pretty much like a function in Javascript. Of course, if you want to pass arguments, you'd have to make your own interface, but those can be implemented anonymously as well. For example, using @Imagist's Function
interface:
interface Function {
Object call(Object[] arguments);
}
// ...
Function helloSayer = new Function(){
public Object call(Object[] args){
System.out.println("Hello, " + args[0] + "!");
}
};
helloSayer.call(new Object[]{ "world" }); // "Hello, world!"
Edit: This has nothing to do with reflection, of course, but there's no reflection in your example either - just an anonymous function.