Skillversitas

Importing Java Libraries

Importing a Java library in Jython is as simple as importing a Python module: write the Java package path with dots and use the classes as attributes. No JNI, no wrappers, no configuration beyond putting the jar on the classpath.

Basic Import

import java.util
import java.io
import java.net

lst = java.util.ArrayList()
lst.add("hello")
print(lst.get(0))

f = java.io.File("demo.txt")
print(f.exists())

print(java.net.InetAddress.getLocalHost())

from ... import for Specific Classes

from java.util import HashMap, Collections
from java.lang import System

mp = HashMap()
mp.put("k", "v")
print(mp.get("k"))

print(System.currentTimeMillis())

Constructors and Methods

import java.lang

s = java.lang.StringBuilder()
s.append("Jython").append(" + ").append("Java")
print(s.toString())
print(s.length())

Constructors are called like functions with new omitted (Jython handles the new); overloaded constructors are disambiguated by argument types.

Constants and Static Members

import java.lang
import java.util

print(java.lang.Integer.MAX_VALUE)
print(java.util.Collections.emptyList())

Java Exceptions in Python

import java.io

try:
    java.io.File("no_such_file_xyz.txt").getBytes()
except java.io.IOException as e:
    print("caught:", e)

Java exceptions are catchable in Python except blocks; you can catch the specific Java exception class or the generic Exception.

Classpath Setup

# put jars on the classpath at launch:
jython -cp "libs/common.jar:libs/net.jar" script.py

# or, inside a script before the import:
import sys
sys.classpath.append("libs/common.jar")
import com.example.Foo

When an Import Fails

  • NoClassNotFoundError usually means the jar is missing from the classpath - check -cp.
  • Inner classes use a dollar sign: java.util.Map$Entry is referenced as java.util.Map.Entry in Jython's attribute syntax.
  • Generic type parameters (List<String>) are not written in Jython imports - generics are a compile-time Java concern.

Summary

Import Java libraries with plain import statements (import java.util, from java.util import HashMap), call constructors and statics directly, catch Java exceptions in Python try/except, and manage jars via the -cp flag or sys.classpath. This is Jython's killer feature: the entire Java ecosystem reachable with Python import syntax.