API Reference

JVM Functions

These functions control and start the JVM.

jpype.startJVM(*args, **kwargs)

Starts a Java Virtual Machine. Without options it will start the JVM with the default classpath and jvmpath.

The default classpath is determined by jpype.getClassPath(). The default jvmpath is determined by jpype.getDefaultJVMPath().

Parameters:

*args (Optional, str[]) – Arguments to give to the JVM. The first argument may be the path the JVM.

Keyword Arguments:
 
  • jvmpath (str) – Path to the jvm library file, Typically one of (libjvm.so, jvm.dll, …) Using None will apply the default jvmpath.
  • classpath (str,[str]) – Set the classpath for the JVM. This will override any classpath supplied in the arguments list. A value of None will give no classpath to JVM.
  • ignoreUnrecognized (bool) – Option to ignore invalid JVM arguments. Default is False.
  • convertStrings (bool) – Option to force Java strings to cast to Python strings. This option is to support legacy code for which conversion of Python strings was the default. This will globally change the behavior of all calls using strings, and a value of True is NOT recommended for newly developed code.
  • interrupt (bool) – Option to install ^C signal handlers. If True then ^C will stop the process, else ^C will transfer control to Python rather than halting. If not specified will be False if Python is started as an interactive shell.
Raises:
  • OSError – if the JVM cannot be started or is already running.
  • TypeError – if an invalid keyword argument is supplied or a keyword argument conflicts with the arguments.
jpype.shutdownJVM()

Shuts down the JVM.

This method shuts down the JVM and disables access to existing Java objects. Due to limitations in the JPype, it is not possible to restart the JVM after being terminated.

jpype.getDefaultJVMPath()

Retrieves the path to the default or first found JVM library

Returns:

The path to the JVM shared library file

Raises:
  • JVMNotFoundException – If there was no JVM found in the search path.
  • JVMNotSupportedException – If the JVM was found was not compatible with Python due to cpu architecture.
jpype.getClassPath(env=True)

Get the full Java class path.

Includes user added paths and the environment CLASSPATH.

Parameters:env (Optional, bool) – If true then environment is included. (default True)

Class importing

JPype supports several styles of importing. The newer integrated style is provided by the imports module. The older JPackage method is available for accessing package trees with less error checking. Direct loading of Java classes can be made with JClass.

For convenience, the JPype module predefines the following JPackage instances for java and javax.

class jpype.JPackage(*args, **kwargs)

Gateway for automatic importation of Java classes.

This class allows structured access to Java packages and classes. This functionality has been replaced by jpype.imports, but is still useful in some cases.

Only the root of the package tree needs to be declared with the JPackage constructor. Sub-packages will be created on demand.

For example, to import the w3c DOM package:

Document = JPackage('org').w3c.dom.Document

Under some situations such as a missing jar file, the resulting object will be a JPackage object rather than the expected java class. This results in rather challanging debugging messages. Due to this restriction, the jpype.imports module is preferred. To prevent these types of errors, a package can be declares as strict which prevents expanding package names that do not comply with Java package name conventions.

Parameters:path (str) – Path into the Java class tree.

Example

# Alias into a library
google = JPackage("com").google

# Access members in the library
result = google.common.IntMath.pow(x,m)

Class Factories

class jpype.JClass

Meta class for all Java class instances.

When called as an object, JClass will contruct a new Java class wrapper.

All Python wrappers for Java classes derive from this type. To test if a Python class is a Java wrapper use isinstance(obj, jpype.JClass).

Parameters:

className (str) – name of a Java type.

Keyword Arguments:
 
  • loader (java.lang.ClassLoader) – specifies a class loader to use when creating a class.
  • initialize (bool) – If true the class will be loaded and initialized. Otherwise, static members will be uninitialized.
Returns:

a new wrapper for a Java class

Return type:

JavaClass

Raises:

TypeError – if the component class is invalid or could not be found.

class jpype.JArray(*args, **kwargs)

Creates a Java array class for a Java type of a given dimension.

This serves as a base type and factory for all Java array classes. The resulting Java array class can be used to construct a new array with a given size or specified members.

JPype arrays support Python operators for iterating, length, equals, not equals, subscripting, and slicing. They also support Java object methods, clone, and length property. Java arrays may not be resized, and as such elements cannot be added nor deleted. Currently, applying the slice operator produces a new Python sequence.

Example

# Define a new array class for ``int[]``
IntArrayCls = JArray(JInt)

# Create an array holding 10 elements
#   equivalent to Java ``int[] x=new int[10]``
x = IntArrayCls(10)

# Create a length 3 array initialized with [1,2,3]
#   equivalent to Java ``int[] x = new int[]{1,2,3};``
x = IntArrayCls([1,2,3])

# Operate on an array
print(len(x))
print(x[0])
print(x[:-2])
x[1:]=(5,6)

if isinstance(x, JArray):
     print("object is a java array")

if issubclass(IntArrayCls, JArray):
     print("class is a java array type.")
Parameters:
  • javaClass (str,type) – Is the type of element to hold in the array.
  • ndims (Optional,int) – the number of dimensions of the array (default=1)
Returns:

A new Python class that representing a Java array class.

Raises:

TypeError – if the component class is invalid or could not be found.

Note

javaClass can be specified in three ways:

  • as a string with the name of a java class.
  • as a Java primitive type such as jpype.JInt.
  • as a Java class type such as java.lang.String.
jpype.JException

Java Types

JPype has types for each of the Java primitives: JBoolean, JByte, JShort, JInt, JLong, JFloat and JDouble. There is one class for working with Java objects, JObject. This serves to cast to a specific object type.

class jpype.JObject(*args, **kwargs)

Base class for all object instances.

It can be used to test if an object is a Java object instance with isinstance(obj, JObject).

Calling JObject as a function can be used to covert or cast to specific Java type. It will box primitive types and supports an option type to box to.

This wrapper functions in three ways.

  • If the no type is given the object is automatically cast to type best matched given the value. This can be used to create a boxed primitive. JObject(JInt(i))
  • If the type is a primitve, the object will be the boxed type of that primitive. JObject(1, JInt)
  • If the type is a Java class and the value is a Java object, the object will be cast to the Java class and will be an exact match to the class for the purposes of matching arguments. If the object is not compatible, an exception will be raised.
Parameters:
  • value – The value to be cast into an Java object.
  • type (Optional, type) – The type to cast into.
Raises:

TypeError – If the object cannot be cast to the specified type, or the requested type is not a Java class or primitive.

Threading

jpype.synchronized(obj)

Creates a resource lock for a Java object.

Produces a monitor object. During the lifespan of the monitor Java will not be able to acquire a thread lock on the object. This will prevent multiple threads from modifying a shared resource.

This should always be used as part of a Python with startment.

Parameters:obj – A valid Java object shared by multiple threads.

Example:

with synchronized(obj):
   # modify obj values

# lock is freed when with block ends
class java.lang.Thread

Thread support for Python

JPype adds methods to java.lang.Thread to interact with Python threads. These methods are all classmethods that act on the current Python thread.

attach()

Attaches the current thread to the JVM as a user thread.

User threads that are attached to the JVM will prevent the JVM from shutting down until the thread is terminated or detached. To convert a daemon thread to a main thread, the thread must first be detached.

Raises:RuntimeError – If the JVM is not running.
attachAsDaemon()

Attaches the current thread to the JVM as a daemon.

Daemon threads act as background tasks and do not prevent the JVM from shutdown normally. JPype automatically attaches any threads that call Java resources as daemon threads. To convert a daemon thread to a user thread, the thread must first be detached.

Raises:RuntimeError – If the JVM is not running.
detach()

Detaches a thread from the JVM.

This function detaches the thread and frees the associated resource in the JVM. For codes making heavy use of threading this should be used to prevent resource leaks. The thread can be reattached, so there is no harm in detaching early or more than once. This method cannot fail and there is no harm in calling it when the JVM is not running.

isAttached()

Checks if a thread is attached to the JVM.

Python automatically attaches as daemon threads when a Java method is called. This creates a resource in Java for the Python thread. This method can be used to check if a Python thread is currently attached so that it can be disconnected prior to thread termination to prevent leaks.

Returns:True if the thread is attached to the JVM, False if the thread is not attached or the JVM is not running.

Decorators

JPype uses ordinary Python classes to implement functionality in Java. Adding these decorators to a Python class will mark them for use by JPype to interact with Java classes.

Proxies

JPype can implement Java interfaces either by using decorators or by manually creating a JProxy. Java only support proxying interfaces, thus we cannot extend an existing Java class.

jpype.JProxy

Customized Classes

JPype provides standard customizers for Java interfaces so that Java objects have syntax matching the corresponding Python objects. The customizers are automatically bound to the class on creation without user intervention. We are documentating the functions that each customizer adds here. Information about Java methods can be found in the Javadoc.

These internal classes can be used as example of how to implement your own customizers for Java classes.

class java.util.Iterable

Customized interface for a container which can be iterated.

JPype wraps java.lang.Iterable as the Python iterator interface.

__iter__()

Iterate over the members on this collect.

__weakref__

list of weak references to the object (if defined)

class java.util.Collection

Customized interface representing a collection of items.

JPype wraps java.util.Collection as a Python collection.

__contains__(item) → bool

Check if this collection contains this item.

Use item in collection to check if the item is present.

Parameters:
  • item – is the item to check for. This must be a Java
  • or an object which can be automatically converted (object) –
  • as a string. (such) –
Returns:

True if the item is in the collection.

Return type:

bool

__delitem__(item)

Collections do not support remove by index.

__len__() → int

Get the length of this collection.

Use len(collection) to find the number of items in this collection.

__weakref__

list of weak references to the object (if defined)

class java.util.List

Customized container holding items in a specified order.

JPype customizes java.lang.List to be equivalent to a Python list. Java list fulfill the contract for collection.abc.MutableSequence.

__add__(obj)

Combine two lists.

Use list + seq to create a new list with additional members. This is only supported if the list can be cloned.

__delitem__(idx: Union[int, slice])

Delete an item by index.

Use del list[idx] to remove ont itme from the list or del list[i0:i1] to remove a section of the list.

__getitem__(ndx)

Access an item or set of items.

Use list[idx] to access a single item or list[i0:i1] to obtain a slice of the list. Slices are views thus changing the view will alter the original list. Slice stepping is not supported for Java lists.

__iadd__(obj)

Add an items to the end of the list.

Use list += obj to append one item. This is simply an alias for add.

__reversed__()

Obtain an iterator that walks the list in reverse order.

Use reversed(list) to traverse a list backwards.

__setitem__(index: Union[int, slice], value)

Set an item on the list.

Use list[idx]=value to set a value on the list or list[i0:i1] = values to replace a section of a list with another list of values.

append(obj)

Append an object to the list.

Parameters:obj – The object to insert.
Raises:TypeError – If the object cannot be converted to Java.
count(obj)

Count the number of times an object appears in a list.

Parameters:obj – A Java object or Python object which automatically converts to Java.
Returns:The number of times this object appears.
Return type:int
extend(lst)

Extends a list by adding a set of elements to the end.

Parameters:lst – A Sequence holding items to be appended.
Raises:TypeError – If the list to be added cannot be converted to Java.
index(obj) → int

Find the index that an item appears.

Parameters:obj – A Java object or Python object which automatically converts to Java.
Returns:The index where the item first appears in the list.
Return type:int
Raises:ValueError – If the item is not on the list.
insert(idx: int, obj)

Insert an object at a specific position.

Parameters:
  • idx – The index to insert the item in front of.
  • obj – The object to insert.
Raises:

TypeError – If the object cannot be converted to Java.

pop(idx=-1)

Remove an item from the list.

Parameters:idx (int, optional) – Position to remove the item from. If not specified the item is removed from the end of the list.
Returns:The item or raises if index is outside of the list.
remove(obj)

Remove an item from the list by finding the first instance that matches.

This overrides the Java method to provide the Python remove. Use lst.remove_ to obtain the Java remove method.

Parameters:obj – Must be a Java object or Python object that can convert to Java automatically.
Raises:ValueError – If the item is not present on the list.
reverse()

Reverse the order of the list in place.

This is equivalent to java.util.Collections.reverse(list).

class java.util.Map

Customized container holding pairs of items like a dictionary.

JPype customizes java.lang.List to be equivalent to a Python list. Java maps fulfill the contract for collection.abc.Mapping.

__contains__(item)

Check if a key is in the map.

Use item in map to verify if the map contains the item. This will return true whether on not the associated value is an object or None.

Returns:True is the key is found.
__delitem__(i)

Remove an item by its key.

Raises:TypeError – If the key cannot be converted to Java.
__getitem__(ndx)

Get a value by its key.

Use map[key] to get the value associate with a key.

Raises:KeyError – If the key is not found in the map or the key cannot be converted to Java.
__iter__()

Iterate the keys of the map.

__len__()

Get the number of items in this map.

Use len(map) to get the number of items in the map.

__setitem__(key, value)

Set a value associated with a key..

Use map[key]=value to set the value associate with a key.

Raises:TypeError – If the key or value cannot be converted to Java.
__weakref__

list of weak references to the object (if defined)

items()

Get a list of entries in the map.

The map entries are customized to appear as tuples with two items. Maps can traversed as key value pairs using map.items()

keys() → list

Get a list of keys for this map.

Use map.keySet() to obtain the keys as Java views them.

Returns:A Python list holding all of the items.
Return type:list
class java.util.Set

Customized Java Sets.

Java sets only provide the ability to delete items.

class java.util.Iterator

Customized Java Iterator.

Java iterators act just like Python iterators for the purposed of list comprehensions and foreach loops.

class java.util.Enumeration

Customized Java enumeration.

Enumerations are used rarely in Java, but can be iterated like a Java iterable using Python.

class java.lang.AutoCloseable

Customizer for java.lang.AutoCloseable and java.io.Closeable

This customizer adds support of the with operator to all Java classes that implement the Java AutoCloseable interface.

Example:

from java.nio.files import Files, Paths
with Files.newInputStream(Paths.get("foo")) as fd:
  # operate on the input stream

# Input stream closes at the end of the block.

Modules

Optional JPype behavior is stored in modules. These optional modules can be imported to add additional functionality.

JPype Imports Module

Once imported this module will place the standard Top Level Domains (TLD) into the Python scope. These TLDs are java, com, org, gov, mil, net and edu. Java symbols from these domains can be imported using the standard Python syntax.

Import customizers are supported in Python 3.6 or greater.

Forms supported:
  • import <java_pkg> [ as <name> ]
  • import <java_pkg>.<java_class> [ as <name> ]
  • from <java_pkg> import <java_class>[,<java_class>*]
  • from <java_pkg> import <java_class> [ as <name> ]
  • from <java_pkg>.<java_class> import <java_static> [ as <name> ]
  • from <java_pkg>.<java_class> import <java_inner> [ as <name> ]

For further information please read the JImport guide.

Requires:
Python 3.6 or later

Example:

import jpype
import jpype.imports
jpype.startJVM()

# Import java packages as modules
from java.lang import String

JPype Pickle Module

This module contains overloaded Pickler and Unpickler classes that operate on Java classes. Pickling of Java objects is restricted to classes that implement Serializable. Mixed pickle files containing both Java and Python objects are allowed. Only one copy of each Java object will appear in the pickle file even it is appears multiple times in the data structure.

JPicklers and JUnpickler use Java ObjectOutputStream and ObjectInputStream to serialize objects. All of the usual Java serialization errors may be thrown.

This is backed by the native cPickler implementation.

Example:

myobj = jpype.JClass('java.util.ArrayList')()
myobj.add("test")

from jpype.pickle import JPickler, JUnpickler
with open("test.pic", "wb") as fd:
  JPickler(fd).dump(myobj)

with open("test.pic", "rb") as fd:
  newobj = JUnpickler(fd).load()

Proxies and other JPype specific module resources cannot be pickled currently.

Requires:
Python 3.6 or later
class jpype.pickle.JPickler(file, *args, **kwargs)

Pickler overloaded to support Java objects

Parameters:
  • file – a file or other writeable object.
  • *args – any arguments support by the native pickler.
Raises:
  • java.io.NotSerializableException – if a class is not serializable or one of its members
  • java.io.InvalidClassException – an error occures in constructing a serialization.
class jpype.pickle.JUnpickler(file, *args, **kwargs)

Unpickler overloaded to support Java objects

Parameters:
  • file – a file or other readable object.
  • *args – any arguments support by the native unpickler.
Raises:
  • java.lang.ClassNotFoundException – if a serialized class is not found by the current classloader.
  • java.io.InvalidClassException – if the serialVersionUID for the class does not match, usually as a result of a new jar version.
  • java.io.StreamCorruptedException – if the pickle file has been altered or corrupted.

JPype Beans Module

This customizer finds all occurences of methods with get or set and converts them into Python properties. This behavior is sometimes useful in programming with JPype with interactive shells, but also leads to a lot of confusion. Is this class exposing a variable or is this a property added JPype.

As an unnecessary behavior that violates both the Python principle “There should be one– and preferably only one –obvious way to do it.” and the C++ principle “You only pay for what you use”. This misfeature was removed from the distribution as a default. However, given that it is useful to have methods appear as properties, it was moved to a an optional module.

To use beans as properties:

import jpype.beans

The beans property modification is a global behavior and applies retroactively to all classes currently loaded. Once started it can not be undone.

JPype Types Module

Optional module containing only the Java types and factories used by JPype. Classes in this module include JArray, JClass, JBoolean, JByte, JChar, JShort, JInt, JLong, JFloat, JDouble, JString, JObject, and JException.

Example

from jpype.types import *