API Reference

JVM Functions

These functions control and start the JVM.

jpype.startJVM(*jvmargs: str, jvmpath: Optional[_PathOrStr] = None, classpath: Union[Sequence[_PathOrStr], _PathOrStr, None] = None, ignoreUnrecognized: bool = False, convertStrings: bool = False, interrupt: bool = True) None

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().


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

Keyword Arguments:
  • jvmpath (str, PathLike) – Path to the jvm library file, Typically one of (libjvm.so, jvm.dll, …) Using None will apply the default jvmpath.

  • classpath (str, PathLike, [str, PathLike]) – 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.

  • OSError – if the JVM cannot be started or is already running.

  • TypeError – if a keyword argument conflicts with the positional arguments.


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.


Retrieves the path to the default or first found JVM library


The path to the JVM shared library file

  • 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: bool = True) str

Get the full Java class path.

Includes user added paths and the environment CLASSPATH.


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


Decorator to register a function to be called after JVM is started.

This can be used to load module resources that depend on the JVM such as loading classes. If the JVM is not started, the user supplied function is held in a list until the JVM starts. When startJVM is called, all functions on the deferred list are called and the list is cleared. If the JVM is already started, then the function is called immediately.

Errors from the function will either be raised immediately if the JVM is started, or from startJVM if the JVM is not yet started.


func (callable) – a function to call when the JVM is started.

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.


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


# 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(jc, loader=None, initialize=True)

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).


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.


a new wrapper for a Java class

Return type:



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

class jpype.JArray(tp, dims=1)

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.


# 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

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

if issubclass(IntArrayCls, JArray):
     print("class is a java array type.")
  • 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)


A new Python class that representing a Java array class.


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


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.

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

Base class for all java.lang.Throwable objects.

Use issubclass(cls, JException) to test if a class is derived from java.lang.Throwable.

Use isinstance(obj, JException) to test if an object is a java.lang.Throwable.

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.

  • value – The value to be cast into an Java object.

  • type (Optional, type) – The type to cast into.


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



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.


obj – A valid Java object shared by multiple threads.


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() None

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.


RuntimeError – If the JVM is not running.

attachAsDaemon() None

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.


RuntimeError – If the JVM is not running.

detach() None

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() bool

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.


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


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.

@jpype.JConversion(cls, exact=None, instanceof=None, attribute=None, excludes=None)

Decorator to define a method as a converted a Java type.

Whenever a method resolution is called the JPype internal rules are applied, but this may be insufficient. If only a single method requires modification then a class customizer can be applied. But if many interfaces require the same conversion than a user conversion may be a better option.

To add a user conversion define a method which take the requested Java type as the first argument, the target object to be converted as the second argument and returns a Java object or Java proxy that matches the required type. If the type is not a Java type then a TypeError will be raised. This method is only evaluated after the match has been determine prior to calling.

Care should be used when defining a user conversion. If example if one has an interface that requires a specific class and you want it to take a Python string, then a user conversion can do that. On the other hand, if you define a generic converter of any Python object to a Java string, then every interface will attempt to call the conversion method whenever a Java string is being matched, which can cause many methods to potentially become ambiguous.

Conversion are not inherited. If the same converter needs to apply to multiple types, then multiple decorators can be applied to the same method.

  • cls (str, JClass) – The class that will be produced by this conversion.

  • exact (type) – This conversion applies only to objects that have a type exactly equal to the argument.

  • instanceof (type or protocol) – This conversion applies to any object that passes isinstance(obj, type).

  • attribute (str) – This conversion applies to any object that has passes hasattr(obj, arg). (deprecated)

  • excludes (type) – Prevents a conversion for a specified type. Can be used to prevent a specific type from being converted. For example, to prevent maps or strings from passing a check for Sequence. Exclusions are applied before all other user specificied conversions.

@jpype.JImplementationFor(clsname, base=False)

Decorator to define an implementation for a class.

Applies to a class which will serve as a prototype as for the Java class wrapper. If it is registered as a base class, then the class must derive from JObject. Otherwise, the methods are copied from the prototype to the Java class wrapper.

The method __jclass_init__(cls) will be called with the constructed class as the argument. This call is used to set methods for all classes that derive from the specified class. Use jclass._customize() to alter the class methods.

Using the prototype class as a base class is used mainly to support classes which must be derived from a Python type by design. Use of a base class will produce a RuntimeError if the class has already been created.

For non-base class customizers, the customizer will be applied retroactively if the class is already created. Conflicts are resolved by the last customizer applied.

  • clsname (str) – name of java class.

  • base (bool, optional) – if True this will be a base class. Default is False.

@jpype.JImplements(*interfaces, deferred=False, **kwargs)

Annotation for creating a new proxy that implements one or more Java interfaces.

This annotation is placed on an ordinary Python class. The annotation requires a list of interfaces. It must implement all of the java methods for each of the interfaces. Each implemented method should have a @JOverride annotation. The JVM must be running in order to validate the class.


interfaces (str*,JClass*) – Strings or JClasses for each Java interface this proxy is to implement.

deferred (bool):

Whether to defer validation of the interfaces and overrides until the first instance instantiation (True) or validate at declaration (False). Deferred validation allows a proxy class to be declared prior to starting the JVM. Validation only occurs once per proxy class, thus there is no performance penalty. Default False.


class MyImpl(object):
   def run(self, arg):

@JImplement("org.my.Interface1", "org.my.Interface2")
class MyImpl(object):
   def method(self, arg):
@jpype.JOverride(*args, **kwargs)

Annotation to denote a method as overriding a Java method.

This annotation applies to customizers, proxies, and extensions to Java classes. Apply it to methods to mark them as implementing or overriding Java methods. Keyword arguments are passed to the corresponding implementation factory.


sticky=bool – Applies a customizer method to all derived classes.


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.

class jpype.JProxy(intf, dict=None, inst=None, convert=False)

Define a proxy for a Java interface.

This is an older style JPype proxy interface that uses either a dictionary or an object instance to implement methods defined in java. The python object can be held by java and its lifespan will continue as long as java holds a reference to the object instance. New code should use @JImplements annotation as it will support improved type safety and error handling.

Name lookups can either made using a dictionary or an object instance. One of these two options must be specified.

  • intf – either a single interface or a list of java interfaces. The interfaces can either be defined by strings or JClass instance. Only interfaces may be used in a proxy,

  • dict (dict[string, callable], optional) – specifies a dictionary containing the methods to be called when executing the java interface methods.

  • inst (object, optional) – specifies an object with methods whose names matches the java interfaces methods.

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.


Iterate over the members on this collect.


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.

  • item – is the item to check for. This must be a Java

  • converted (object or an object which can be automatically) –

  • string. (such as a) –


True if the item is in the collection.

Return type:



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.


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.


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: 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.


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.


Add an items to the end of the list.

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


Obtain an iterator that walks the list in reverse order.

Use reversed(list) to traverse a list backwards.

__setitem__(index: 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 an object to the list.


obj – The object to insert.


TypeError – If the object cannot be converted to Java.


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


obj – A Java object or Python object which automatically converts to Java.


The number of times this object appears.

Return type:



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


lst – A Sequence holding items to be appended.


TypeError – If the list to be added cannot be converted to Java.

index(obj) int

Find the index that an item appears.


obj – A Java object or Python object which automatically converts to Java.


The index where the item first appears in the list.

Return type:



ValueError – If the item is not on the list.

insert(idx: int, obj)

Insert an object at a specific position.

  • idx – The index to insert the item in front of.

  • obj – The object to insert.


TypeError – If the object cannot be converted to Java.


Remove an item from the list.


idx (int, optional) – Position to remove the item from. If not specified the item is removed from the end of the list.


The item or raises if index is outside of the list.


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.


obj – Must be a Java object or Python object that can convert to Java automatically.


ValueError – If the item is not present on the list.


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.


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.


True is the key is found.


Remove an item by its key.


TypeError – If the key cannot be converted to Java.


Get a value by its key.

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


KeyError – If the key is not found in the map or the key cannot be converted to Java.


Iterate the keys of the map.


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.


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


list of weak references to the object (if defined)


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.


A Python list holding all of the items.

Return type:


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.


from java.nio.file 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.


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.

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.


import jpype
import jpype.imports

# 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.


myobj = jpype.JClass('java.util.ArrayList')()

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

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

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

class jpype.pickle.JPickler(file, *args, **kwargs)

Pickler overloaded to support Java objects

  • file – a file or other writeable object.

  • *args – any arguments support by the native pickler.

  • 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

  • file – a file or other readable object.

  • *args – any arguments support by the native unpickler.

  • 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.


from jpype.types import *