- Closure data types are converted to inner classes at compile time.
- AnnonymousClassLoader in MLVM, allows us to load multiple definitions of same class in the same instance of the class loader at run time.
import java.dyn.AnonymousClassLoader;Output:
public class CustomizableClosure {
static private {String => void} welcomeClosure =
{ String name => System.out.println(name + ", " + shortWelcome);};
static String shortWelcome = " Welcome to closure...";
static String detailedWelcome =
" Welcome to MLVM closure customization..Experience the power of AnonymousClassLoader...";
public static void main(String[] args) throws Exception {
CustomizableClosure.testSimpleClosure();
CustomizableClosure.testCustomizableClosure();
}
static void testSimpleClosure() {
System.out.println("=================");
System.out.println("Before customization..");
welcomeClosure.invoke("Dear bob");
System.out.println("=================");
}
static void testCustomizableClosure() throws Exception {
AnonymousClassLoader acl = new AnonymousClassLoader();
acl.setClassFile(welcomeClosure.getClass());
Class hostClass = CustomizableClosure.class;
Class acls = welcomeClosure.getClass();
acl.putSymbolPatch("shortWelcome", "detailedWelcome");
acls = acl.loadClass();
{String => void} obj = ({String => void}) acls.newInstance();
System.out.println("================");
System.out.println("After customization..");
obj.invoke("Dear bob");
System.out.println("================");
}
}
=================
Before customization..
Dear bob, Welcome to closure...
=================
================
After customization..
Dear bob, Welcome to MLVM closure customization..Experience the power of AnonymousClassLoader...
=================
OK, what's going on?
- {String => void} welcomeClosure = { String name => System.out.println(name + ", " + shortWelcome);} this closure snippet is converted to inner class at compile time.
- In method "testSimpleClosure", we are executing closure code as is.
- In method "testCustomizableClosure", we take closure (compiled inner class) as base template, customize it (by changing welcome text) at run time and execute it.
- Build OpenJDK and Hotspot.
- Apply MLVM patch and rebuild Hotspot.
- Download javac for closures from javac.info
- Prepend MLVM AnonymousClassLoader.class and javac.jar to bootclasspath of java and javac. In my local machine, i used following commands for compilation and execution.
- javac -J-Xbootclasspath/p:/share/software/OpenJDK/closures-2008-02-12/lib/javac.jar:/share/software/OpenJDK/mlvm/bootcp -source 7 -d classes/ CustomizableClosure.java
- java -Xbootclasspath/p:/share/software/OpenJDK/closures-2008-02-12/lib/javac.jar:/share/software/OpenJDK/mlvm/bootcp -cp classes CustomizableClosure