DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Using Python Libraries in Java
  • Memory Leak Due To Mutable Keys in Java Collections
  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Squid Game: The Clean Code Trials — A Java Developer's Survival Story

Trending

  • Advancing DSLs in the Age of GenAI
  • Top 5 Trends in Big Data Quality and Governance in 2025
  • Exploring Data Redaction Enhancements in Oracle Database 23ai
  • When Caches Collide: Solving Race Conditions in Fare Updates
  1. DZone
  2. Coding
  3. Java
  4. Embed Jython to Your Java Codebase

Embed Jython to Your Java Codebase

Follow along with this quick and easy example for those looking to include some Jython into a Java app.

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
Oct. 20, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
11.5K Views

Join the DZone community and get the full member experience.

Join For Free

Jython is a great tool for some quick Java scripts using a pretty solid syntax. Actually, it works wonderfully when it comes to implementing some maintenance or monitoring scripts with

If you work with other teams that have a Python background, it makes absolute sense to integrate Python to your Java applications.

First, let’s import the Jython interpreter using the standalone version.

group 'com.gkatzioura'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.5

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile group: 'org.python', name: 'jython-standalone', version: '2.7.0'
}

The easiest thing to do is just to execute a Python file in our class path. The file would be hello_world.py

 print "Hello World" 

And then pass the file as an inputstream to the interpeter

package com.gkatzioura;

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

import java.io.InputStream;

/**
 * Created by gkatzioura on 19/10/2016.
 */
public class JythonCaller {

    private PythonInterpreter pythonInterpreter;

    public JythonCaller() {
        pythonInterpreter = new PythonInterpreter();
    }

    public void invokeScript(InputStream inputStream) {

        pythonInterpreter.execfile(inputStream);
    }

}
 @Test public void testInvokeScript() { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("hello_world.py"); jythonCaller.invokeScript(inputStream); } 

The next step is to create a Python class file and another Python file that will import the class file and instantiate a class.

The class file would be divider.py.

class Divider:

    def divide(self,numerator,denominator):

        return numerator/denominator;

And the file importing the Divider class would be classcaller.py

from divider import Divider

divider = Divider()

print divider.divide(10,5);

So let us test it

@Test
public void testInvokeClassCaller() {

    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("classcaller.py");
    jythonCaller.invokeScript(inputStream);
} 

What we can understand from this example is that the interpreter successfully imports the files from the classpath.

Running files using the interpreter is OK, however, we need to fully utilize classes and functions implemented in Python.

Therefore, the next step is to create a Python class and use its functions using Java.

package com.gkatzioura;

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

import java.io.InputStream;

/**
 * Created by gkatzioura on 19/10/2016.
 */
public class JythonCaller {

    private PythonInterpreter pythonInterpreter;

    public JythonCaller() {
        pythonInterpreter = new PythonInterpreter();
    }

    public void invokeClass() {

        pythonInterpreter.exec("from divider import Divider");
        PyClass dividerDef = (PyClass) pythonInterpreter.get("Divider");
        PyObject divider = dividerDef.__call__();
        PyObject pyObject = divider.invoke("divide",new PyInteger(20),new PyInteger(4));

        System.out.println(pyObject.toString());
    }

}


You can find the source code on GitHub.

Java (programming language) Jython

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Using Python Libraries in Java
  • Memory Leak Due To Mutable Keys in Java Collections
  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Squid Game: The Clean Code Trials — A Java Developer's Survival Story

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: