Call Java class method from Python using Jpype
If you already have alot of Java classes written, you can reuse that code in Python using Jpype. Jypype works by interfacing at the native level in both Python and Java VMs. In order to reuse Java classes, you must have Jpype installed. The easiest way to install Jpype is to use Pip, an add in package manager for Python. If you are using Python2, versions 2.7.9 or higher already Pip installed. If you are using Python3, versions 3.4 or higher already have Pip installed.
To install Jpype, type in the following command :
pip install Jpype
Once you have Jpype installed, you need to find the path to your jvm.dll installation. One you have that information, you can create a new python file and include Jpype by the following line :
import jpype
Next, start the java virtual machine with the following line where PATH_TO_JVM is the path to your jvm.dll:
jpype.startJVM(PATH_TO_JVM, "-ea")
Next, instantiate the java object in Python with the following lines where PACKAGE_NAME is the java package name and CLASS_NAME is the java class name :
javaPackage = jpype.JPackage("PACKAGE_NAME")
jClass = javaPackage.CLASS_NAME
jObject = jClass()
To make a call to a java method, with the following where METHOD_NAME is the java method you wish to call. Finally, shutdown the java virtual machine.
To call java method
jObject.METHOD_NAME()
To shutdown the java virtual machne
jpype.shutdownJVM()