The power of Jython: build your first Java-Python hybrid application in 5 minutes

Rostyslav Ivankiv
2 min readApr 8, 2023

--

Introduction

Python nowdays is a popular and widely-used programming language, known for its ease of use. Java, on the other hand, is a powerful and popular language that is widely used for enterprise development. What if you could combine the power of Python with Java to create a hybrid application that leverages the strengths of both languages? Enter Jython[1], a Python implementation for the Java platform.

So, let’s dive in and see how Jython can take your development to the next level!

Picture 1 — Logo[1]

Code

Let’s go straignt to the code. We will need jython-slim jar as a dependency in our pom.xml, some Python script.py with a code. And finally we may invoke the Python function from Java to calculate the result and print it in Main.java.

See pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>jython-example</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-slim</artifactId>
<version>2.7.3</version>
</dependency>
</dependencies>
</project>

See script.py

def add(x, y):
return x + y

See Main.java

package com.example;

import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class Main {
public static void main(String[] args) {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.execfile(ClassLoader.getSystemResourceAsStream("script.py"));
PyObject sumFunction = pyInterp.get("add");
PyObject sum = sumFunction.__call__(new PyInteger(2), new PyInteger(2));
System.out.println("Sum: " + sum.asInt());
}
}
}

Output:

Sum: 4

Conclusions

Jython is a powerful tool that allows you to combine the strengths of Python and Java to create hybrid applications that are both powerful and easy to develop.

However, it’s important to note that Jython does have some limitations. For example:

It can use libraries written in pure Python. So you can use many libraries like requests, flask etc. Libraries with C extensions like BeautifulSoup, Numpy, Cython, Scipy, Falcon etc cannot be used[2]

And

The current release (a Jython 2.7.x) only supports Python 2 (sorry)[1]

Despite these limitations, Jython remains a valuable tool for developers who want to create powerful, flexible applications that take advantage of both Python and Java.

References

  1. https://www.jython.org/
  2. https://www.quora.com/Can-Jython-use-Python-libraries

--

--