These functions control and start the JVM.
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
*args (Optional, str) – Arguments to give to the JVM. The first argument may be the path the JVM.
- jvmpath (str) – Path to the jvm library file,
Typically one of (
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.
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 (
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.
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.
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)
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 JPpype module predefines the following
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
JPackageconstructor. 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.importsmodule is preferred. To prevent these types of errors a package can be declares as
strictwhich prevents expanding package names that do not comply with Java package name conventions.
- 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.
# Alias into a library google = JPackage("com.google") # Access members in the library result = google.common.IntMath.pow(x,m)
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
className (str) – name of a java type.
- 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.
a new wrapper for a Java class
TypeError– if the component class is invalid or could not be found.
Base class for all
When called as an object
JExceptionwill produce a new exception class. The arguments may either be a string or an existing Java throwable. This functionality is deprecated as exception classes can be created with
issubclass(cls, JException)to test if a class is derived from
isinstance(obj, JException)to test if an object is a
JPype has types for each of the Java primitives:
JDouble. In addition
there is one class for working with Java objects,
JObject. These serve
to be able to cast to a specified type and specify types with the
factory. There is a
JString type provided for convenience when creating
or casting to strings.
Base class for all object instances.
It can be used to test if an object is a java object instance with
JObjectas 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.
- If the type is a primitve, the object will be the boxed type of that
- 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.
- 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.
- 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.
Base class for
When called as a function, this class will produce a
java.lang.Stringobject. It can be used to test if an object is a Java string using
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
Parameters: obj – A valid Java object shared by multiple threads.
with synchronized(obj): # modify obj values # lock is freed when with block ends
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.
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.
RuntimeError– If the JVM is not running.
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.
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 can implement Java interfaces either using decorators or by manually creating a JProxy. Java only support proxying interfaces, thus we cannot extend an existing Java class.
JProxy(intf, dict=None, inst=None)¶
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
@JImplementsannotation 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.
JPype provides standard customizers for Java interfaces so that Java objects have syntax matching the corresponding Python objects. The customizers are automatically bound 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.
This customizer adds the Python iterator syntax to classes that implement Java Iterable.
This customizer adds the Python functions
delto Java Collions to allow for Python syntax.
This customizer adds the Python list operator to function on classes that implement the Java List interface.
This customizer adds the Python list and len operators to classes that implement the Java Map interface.
This customizer adds the Python iterator concept to classes that implement the Java Iterator interface.
This customizer adds the Python iterator concept to classes that implement the Java Enumerator interface.
This customizer adds support of the with operator to all Java classes that implement Java Closable interface.
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.
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
symbols from these domains can be imported using the standard Python
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.
- Python 2.7 or 3.6 or later
import jpype import jpype.imports jpype.startJVM() # Import java packages as modules from java.lang import String
Add a java domain to python as a dynamic module.
This can be used to bind a Java path to a Python path.
- 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.
Import customizers can be used to import python packages into java modules automatically.
Base class for Import customizer.
Import customizers should implement canCustomize and getSpec.
# 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 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:
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
from jpype.types import *