Search code examples
javapythonjython

How to import a java class i created in jython and call a method


I have made a java class that calls other java classes and then prints to a screen. i am trying to build a python interface that calls my java class, runs the one method within it, and terminates. i cannot get access to my method. i have used the line "import directory.directory2.myClass.java (and .jar and .class) i made the .jar file from both the raw code and from the .class file. none of these seem to be working. i set sys.path.append to point to the directory where the java files are. Do i need to convert my java class file to a python module? and if so how do i do that?


Solution

  • Jython supports loading Java classes as if they were Python modules. It searches the directories in sys.path for .class files.

    First, make sure your Java class has already been compiled with javac.

    Then, do a sys.path.append(d), where d is the directory containing the package. So if your class says package foo.bar; at the top, and resides at mydir/foo/bar/myclass.java, then you must have mydir in sys.path (NOT one of the subdirs of mydir).

    Finally, import the class via something like from foo.bar import myclass. The names between must match up between Python and Java! You'll be doing "from [package] import [class]".