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 byjpype.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 JVM to ignore invalid JVM arguments. Default is False.
- convertStrings (bool) –
Option to JPype 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.
The default value for this option during 0.7 series is True. The option will be False starting in 0.8. A warning will be issued if this option is not specified during the transition period.
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.
- jvmpath (str) – Path to the jvm library file,
Typically one of (
-
jpype.
shutdownJVM
()¶ Shuts down the JVM.
This method shuts down the JVM and thus 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
(name, strict=False, pattern=None)¶ 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 need 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 the resulting object will be a JPackage object rather than the expected java class. This results in rather challanging debugging messages. Thus the
jpype.imports
module is preferred. To prevent these types of errors a package can be declares asstrict
which prevents expanding package names that do not comply with Java package name conventions.Parameters: - path (str) – Path into the Java class tree.
- strict (bool, optional) – Requires Java paths to conform to the Java package naming convention. If a path does not conform and a class with the required name is not found, the AttributeError is raise to indicate that the class was not found.
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.
JClass when called as an object will contruct a new java Class wrapper.
All python wrappers for java classes derived 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) – Passed to class loader when loading a class using the class loader.
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)¶ Create 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 members.
JPype arrays support Python operators for iterating, length, equals, not equals, subscripting, and limited slicing. They also support Java object methods, clone, and length property. Java arrays may not be resized, thus 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. There is a JString
type provided for convenience
when creating or casting to strings.
-
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 four 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.
- If the value is a python wrapper for class it will create a class
instance. This is aliased to be much more obvious as the
class_
member of each Java class.
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.- 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.
-
class
jpype.
JString
(*args, **kwargs)¶ Base class for
java.lang.String
objectsWhen called as a function, this class will produce a
java.lang.String
object. It can be used to test if an object is a Java string usingisinstance(obj, JString)
.
Threading¶
-
jpype.
synchronized
(obj)¶ Creates a resource lock for a Java object.
Produces a monitor object. During the lifespan of the monitor the 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
-
jpype.
isThreadAttachedToJVM
()¶ Checks if a thread is attached to the JVM.
Python automatically attaches 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.
-
jpype.
attachThreadToJVM
()¶ Attaches a thread to the JVM.
The function manually connects a thread to the JVM to allow access to Java objects and methods. JPype automaticatlly attaches when a Java resource is used, so a call to this is usually not needed.
Raises: RuntimeError
– If the JVM is not running.
-
jpype.
detachThreadFromJVM
()¶ 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.
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.
These internal classes can be used as example of how to implement your own customizers for Java classes.
-
class
jpype._jcollection.
_JIterable
¶ Customizer for
java.util.Iterable
This customizer adds the Python iterator syntax to classes that implement Java Iterable.
-
class
jpype._jcollection.
_JCollection
¶ Customizer for
java.util.Collection
This customizer adds the Python functions
len()
anddel
to Java Collions to allow for Python syntax.
-
class
jpype._jcollection.
_JList
¶ Customizer for
java.util.List
This customizer adds the Python list operator to function on classes that implement the Java List interface.
-
class
jpype._jcollection.
_JMap
¶ Customizer for
java.util.Map
This customizer adds the Python list and len operators to classes that implement the Java Map interface.
-
class
jpype._jcollection.
_JIterator
¶ Customizer for
java.util.Iterator
This customizer adds the Python iterator concept to classes that implement the Java Iterator interface.
-
class
jpype._jcollection.
_JEnumeration
¶ Customizer for
java.util.Enumerator
This customizer adds the Python iterator concept to classes that implement the Java Enumerator interface.
-
class
jpype._jio.
_JCloseable
¶ Customizer for
java.lang.AutoCloseable
andjava.io.Closeable
This customizer adds support of the with operator to all Java classes that implement 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 TLDs 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.imports.
registerDomain
(mod, alias=None)¶ Add a java domain to python as a dynamic module.
This can be used to bind a Java path to a Python path.
Parameters: - mod (str) – Is the Python module to bind to Java.
- alias (str, optional) – Is the name of the Java path if different than the Python name.
-
jpype.imports.
registerImportCustomizer
(customizer)¶ Import customizers can be used to import python packages into java modules automatically.
-
class
jpype.imports.
JImportCustomizer
¶ Base class for Import customizer.
Import customizers should implement canCustomize and getSpec.
Example:
# Site packages for each java package are stored under $DEVEL/<java_pkg>/py class SiteCustomizer(jpype.imports.JImportCustomizer): def canCustomize(self, name): if name.startswith('org.mysite') and name.endswith('.py'): return True return False def getSpec(self, name): pname = name[:-3] devel = os.environ.get('DEVEL') path = os.path.join(devel, pname,'py','__init__.py') return importlib.util.spec_from_file_location(name, path)
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 pickles 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 serial objects. All of the usual java serialization errors may be thrown.
For Python 3 series, 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.load(fd)
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 membersjava.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 occurances 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. It was the default behavior until 0.7.
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”. Thus this misfeature was removed from the distribution as a default. However, given that it is at times 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 never 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 *