Chapter 6. Using Java from Jython

This chapter covers the use of Java classes from Jython code. From Jython, you have access to all the Java classes in all standard libraries, any third-party libraries, and, of course, your own Java code. Jython leverages Python’s object-oriented structures and support to integrate smoothly with Java.

Basic Object Usage

In Importing Java Classes in Chapter 4, we showed how you can retrieve Java classes using the import statement. The Jython runtime wraps both Java classes and instances inside proxy objects, which offer a natural and intuitive mix between what you expect from Java semantics and what you have learned so far about user-defined Python classes. Using these objects, Jython provides a number of automatic conversions when passing objects back and forth between Jython and Java code.

When using a Java class in Jython, you can, by default, access all inner classes, static fields, static methods, and instance methods—as long as they are defined as public. If you need to get access to protected or private members, you can set the Jython registry option python.security.respectJavaAccessibility = false, an option used mainly for testing. The following code shows how you can import and then use Java classes and methods from the interpreter:

>>> from java.lang import System
>>> System.out.println("print would be more pythonic")
print would be more pythonic

You construct Java instances the same way you construct Python instances, by calling the class ...

Get Jython Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.