Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to insert java code into a jython program. The java code is automatically compiled and the resulting class is imported and returned. Compilation only occurs after a change of the java source.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import jythonc, sys
def java(code, force=0):
	"""compile code snippet and return imported class"""
	codelines=code.split(";")
	for line in codelines:
		if line.find("class")!= -1:
			classname=line[line.find("class"):].split()[1]
			break
	try:
		oldcode=open(classname+".java").readlines()
	except:
		oldcode=""
	print >> open(classname+".java","w") ,code
	code=open(classname+".java").readlines()
	if(oldcode!=code or force!=0):
		retcode,retout,reterr=jythonc.javac.compile([classname+".java",])
		if retcode!=0:
			raise RuntimeError, reterr
	return sys.builtins["__import__"](classname)
		

if __name__=="__main__":
	java("""
	// this is the embedded java code
	public class inlined_java {
		public static void main() {
			System.out.println("Hello World from jython!!!");
		}
	}
	""",force=1).main()

Using this recipe java code can be generated dynamically. As long as the java code does not change no compilation is performed. One can also use the recipe for an incremental transition from jython source to java source. This fits very well into the python philosophy of writing the time consuming parts of a program in a fast programming language, while the overall logic is still implemented in jython. In principle one can generalize the approach to different programming languages on the JVM like jruby, jscheme, jacl and so on.