SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы

Назад

Building Java Classes from Python


Метки: python

Part of the trick of creating Java classes from Python code is the @sig information in the method documentation strings. But there’s a second problem which stems from the fact that Python has no “package” keyword – the Python equivalent of packages (modules) are implicitly created based on the file name. However, to bring the resulting class files into the Java program, jythonc must be given information about how to create the Java package for the Python code. This is done on the jythonc command line using the –package flag, followed by the package name you wish to produce (including the separation dots, just as you would give the package name using the package keyword in a Java program). This will put the resulting .class files in the appropriate subdirectory off of the current directory. Then you only need to import the package in your Java program, as shown above (you’ll need ‘.‘ in your CLASSPATH in order to run it from the code directory).

Here are the make dependency rules that I used to build the above example (the backslashes at the ends of the lines are understood by make to be line continuations):

TestPythonToJavaClass.class: \\
        TestPythonToJavaClass.java \\
        python\java\test\PythonToJavaClass.class
    javac TestPythonToJavaClass.java

python\java\test\PythonToJavaClass.class: \\
        PythonToJavaClass.py
    jythonc.bat --package python.java.test \\
    PythonToJavaClass.py

The first target, TestPythonToJavaClass.class, depends on both TestPythonToJavaClass.java and the PythonToJavaClass.class, which is the Python code that’s converted to a class file. This latter, in turn, depends on the Python source code. Note that it’s important that the directory where the target lives be specified, so that the makefile will create the Java program with the minimum necessary amount of rebuilding.