Skip to content

Instantly share code, notes, and snippets.

@ddimtirov
Created November 2, 2013 06:46
Show Gist options
  • Save ddimtirov/7276296 to your computer and use it in GitHub Desktop.
Save ddimtirov/7276296 to your computer and use it in GitHub Desktop.
Shows how to embed Jython and use it as a code generator to create dynamic classes with runtime-defined behavior. Circa 2002.
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class PythonEmbeddedExample {
private static final String EOL = "\n";
private static final PythonInterpreter INTERP = new PythonInterpreter();
private static final String I = "\t";
public static void main(String[] args) throws PyException {
exchangeObjects();
swing();
dynamicImplementations();
calc();
}
private static void calc() {
System.out.println(INTERP.eval("(5+2j)/(-4+12.3j)"));
Object[] arr = (Object[])INTERP.eval("('fafla', 'mafla', 3, 3.14, 3.14-1j)").__tojava__(Object[].class);
for (int i = 0; i < arr.length; i++) {
Object o = arr[i];
System.out.println("o:"+o.getClass()+" = " + o);
}
}
private static void dynamicImplementations() {
TestInterface testInstance = createDynamicImplementation("This is a parameter string");
System.out.println(testInstance.test());
}
private static TestInterface createDynamicImplementation(String retval) {
// define the class
INTERP.exec("import TestInterface" + EOL
+ "class TestImpl(TestInterface):" + EOL
+ " def test(self):" + EOL
+ " return \"" + retval + "\""
);
// instantiate the class
INTERP.exec("testInstance = TestImpl()");
// get instance
return (TestInterface) INTERP.get("testInstance", TestInterface.class);
}
private static void swing() {
INTERP.exec("from pawt import swing" + EOL
+ "import java" + EOL
+ "def exit(e): java.lang.System.exit(0)" + EOL
+ "frame = swing.JFrame('Swing Example', visible = 1)" + EOL
+ "button = swing.JButton('Close Me!', actionPerformed = exit)" + EOL
+ "frame.contentPane.add(button)" + EOL
+ "frame.pack()"
);
}
private static void exchangeObjects() {
System.out.println("Hello, java");
INTERP.exec("import sys" + EOL + "print sys");
INTERP.set("a", new PyInteger(42));
INTERP.exec("print a");
INTERP.exec("x = 2+2");
PyObject x = INTERP.get("x");
System.out.println("x: " + x);
System.out.println("Goodbye, cruel world");
}
}
public interface TestInterface {
String test();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment