In this tutorial we will show you how to integrate Java and Python code in an almost seamless manner with just a few easy steps.
What is jep?
Jep is an open source library which gives you the ability to execute Python code in Java and vice versa.
Let's say you have an existing Java application and you need to use some 3rd party library. Unfortunately, this library is implemented only in Python so you can't really use it as is as part of your application. Jep will help you solve that exact problem.
On a side note, there are other libraries that will help you achieve the same goal like jpy and jython for example, but they are less popular or not as actively maintained as Jep is.
Set up your environment
pip install jep
Install Jep Java library. In case you are using gradle, for example, add the following dependency to your build.gradle:
implementation group: 'black.ninia', name: 'jep', version: '3.9.1'
Finally, you'll need to inject your Java application with a new JVM argument pointing to your Jep Python library installation directory, for example:
-Djava.library.path=/Users/<YOUR_USERNAME>/Library/Python/3.9/lib/python/site-packages/jep
Getting started
Now that everything is setup, we will show you how to work with Jep.
First we'll need to create a new SharedInterpreter instance which we will use throughout our Java code.
Then, using that interpreter, we will:
Inject a String argument which will be used by the Python code: Our Python script argument named user_name will get the value of our Java code name variable.
Execute the Python code using exec() method
Get a return value from Python back to Java
That's it. It's as simple as that.
Now you can install any Python library you need, import it in your Python code and then execute it as part of your Java code.
Running a script
The more common use case for Jep is running an entire Python script with a single Java command. This way you don't need to call the exec() method over and over again for each Python code line you have.
This approach is very useful in case you have an existing Python code which you want executed as part of your Java application.
Type conversion
Every Java type being sent to Python using the interpreter is being converted to its counterpart. This applies to both primitives and complex data structures like objects and collections.
So, for example Python's list will be converted into Java's ArrayList and Python's dict will be converted into Java's HashMap, etc. Everything is done automatically so you don't have to worry about it.
For a full of type conversion, see this link.