Java QuickStart Guide
This is a quick start guide to using JPype with Java. This guide will show a series of snippets with the corresponding commands in both Java and Python for using JPype. The JPype User Guide and API Reference have additional details on the use of the JPype module.
JPype uses two factory classes (JArray
and JClass
) to produce class
wrappers which can be used to create all Java objects. These serve as both the
base class for the corresponding hierarchy and as the factory to produce new
wrappers. Casting operators are used to construct specify types of Java types
(JObject
, JString
, JBoolean
, JByte
, JChar
, JShort
,
JInt
, JLong
, JFloat
, JDouble
). Two special classes serve as the
base classes for exceptions (JException
) and interfaces (JInterface
).
There are a small number of support methods to help in controlling the JVM.
Lastly, there are a few annotations used to create customized wrappers.
For the purpose of this guide, we will assume that the following classes were defined in Java. We will also assume the reader knows enough Java and Python to be dangerous.
package org.pkg;
public class BaseClass
{
public void callMember(int i)
{}
}
public class MyClass extends BaseClass
{
final public static int CONST_FIELD = 1;
public static int staticField = 1;
public int memberField = 2;
int internalField =3;
public MyClass() {}
public MyClass(int i) {}
public static void callStatic(int i) {}
public void callMember(int i) {}
// Python name conflict
public void pass() {}
public void throwsException() throws java.lang.Exception {}
// Overloaded methods
public void call(int i) {}
public void call(double d) {}
}
Starting JPype
The hardest thing about using JPype is getting the jars loaded into the JVM.
Java is curiously unfriendly about reporting problems when it is unable to find
a jar. Instead, it will be reported as an ImportError
in Python.
These patterns will help debug problems with jar loading.
Once the JVM is started Java packages that are within a top level domain (TLD) are exposed as Python modules allowing Java to be treated as part of Python.
Description |
Java |
Python |
---|---|---|
Start Java Virtual Machine (JVM) |
# Import module
import jpype
# Enable Java imports
import jpype.imports
# Pull in types
from jpype.types import *
# Launch the JVM
jpype.startJVM()
|
|
Start Java Virtual Machine (JVM) with a classpath |
# Launch the JVM
jpype.startJVM(classpath = ['jars/*'])
|
|
Import default Java namespace [1] |
import java.lang
|
|
Add a set of jars from a directory [2] |
jpype.addClassPath("/my/path/*")
|
|
Add a specific jar to the classpath [2] |
jpype.addClassPath('/my/path/myJar.jar')
|
|
Print JVM CLASSPATH [3] |
from java.lang import System
print(System.getProperty("java.class.path"))
|
Classes/Objects
Java classes are presented wherever possible similar to Python classes. The
only major difference is that Java classes and objects are closed and cannot be
modified. As Java is strongly typed, casting operators are used to select
specific overloads when calling methods. Classes are either imported using a
module, loaded using JPackage
or loaded with the JClass
factory.
Description |
Java |
Python |
---|---|---|
Import a class [4] |
import org.pkg.MyClass
|
from org.pkg import MyClass
|
Import a class and rename [4] |
from org.pkg import MyClass as OurClass
|
|
Import multiple classes from a package [5] |
from org.pkg import MyClass, AnotherClass
|
|
Import a java package for long name access [6] |
import org.pkg
|
|
Import a class static [7] |
import org.pkg.MyClass.CONST_FIELD
|
from org.pkg.MyClass import CONST_FIELD
|
Import a class without tld [8] |
import zippy.NonStandard
|
NonStandard = JClass('zippy.NonStandard')
|
Construct an object |
MyClass myObject = new MyClass(1);
|
myObject = MyClass(1)
|
Constructing a class with full class name |
import org.pkg
myObject = org.pkg.MyClass(args)
|
|
Get a static field |
int var = MyClass.staticField;
|
var = MyClass.staticField
|
Get a member field |
int var = myObject.memberField;
|
var = myObject.memberField
|
Set a static field [9] |
MyClass.staticField = 2;
|
MyClass.staticField = 2
|
Set a member field [9] |
myObject.memberField = 2;
|
myObject.memberField = 2
|
Call a static method |
MyClass.callStatic(1);
|
MyClass.callStatic(1)
|
Call a member method |
myObject.callMember(1);
|
myObject.callMember(1)
|
Access member with Python naming conflict [10] |
myObject.pass()
|
myObject.pass_()
|
Checking inheritance |
if (obj instanceof MyClass) {...}
|
if (isinstance(obj, MyClass): ...
|
Checking if Java class wrapper |
if (isinstance(obj, JClass): ...
|
|
Checking if Java object wrapper |
if (isinstance(obj, JObject): ...
|
|
Casting to a specific type [11] |
BaseClass b = (BaseClass)myObject;
|
b = (BaseClass) @ myObject
|
Exceptions
Java exceptions extend from Python exceptions and can be dealt with in the same way as Python native exceptions. JException serves as the base class for all Java exceptions.
Description |
Java |
Python |
---|---|---|
Catch an exception |
try {
myObject.throwsException();
} catch (java.lang.Exception ex)
{ ... }
|
try:
myObject.throwsException()
except java.lang.Exception as ex:
...
|
Throw an exception to Java |
throw new java.lang.Exception(
"Problem");
|
raise java.lang.Exception(
"Problem")
|
Checking if Java exception wrapper |
if (isinstance(obj, JException): ...
|
|
Closeable items |
try (InputStream is
= Files.newInputStream(file))
{ ... }
|
with Files.newInputStream(file) as is:
...
|
Primitives
Most Python primitives directly map into Java primitives. However, Python does
not have the same primitive types, and it is necessary to cast to a
specific Java primitive type whenever there are Java overloads that would
otherwise be in conflict. Each of the Java types are exposed in JPype
(JBoolean
, JByte
, JChar
, JShort
, JInt
, JLong
,
JFloat
, JDouble
).
Description |
Java |
Python |
---|---|---|
Casting to hit an overload [12] |
myObject.call((int)v);
|
myObject.call(JInt(v))
|
Create a primitive array |
int[] array = new int[5]
|
array = JInt[5]
|
Create a rectangular primitive array |
int[][] array = new int[5][10]
|
array = JInt[5, 10]
|
Create an array of arrays |
int[][] array = new int[5][]
|
array = JInt[5, :]
|
Create an initialized primitive array [13] |
int[] array = new int[]{1,2,3}
|
array = JInt[:]([1,2,3])
|
Create an initialized boxed array [13] |
Integer[] array = new Integer[]{1,2,3}
|
array = java.lang.Integer[:]([1,2,3])
|
Put a specific primitive type on a list |
List<Integer> myList
= new ArrayList<>();
myList.add(1);
|
from java.util import ArrayList
myList = ArrayList()
myList.add(JInt(1))
|
Boxing a primitive [14] |
Integer boxed = 1;
|
boxed = JObject(JInt(1))
|
Strings
Java strings are similar to Python strings. They are both immutable and produce a new string when altered. Most operations can use Java strings in place of Python strings, with minor exceptions as Python strings are not completely duck typed. When comparing or using as dictionary keys, all JString objects should be converted to Python.
Description |
Java |
Python |
---|---|---|
Create a Java string [15] |
String javaStr = new String("foo");
|
myStr = JString("foo")
|
Create a Java string from bytes [16] |
byte[] b;
String javaStr = new String(b, "UTF-8");
|
b= b'foo'
myStr = JString(b, "UTF-8")
|
Converting Java string |
str(javaStr)
|
|
Comparing Python and Java strings [17] |
str(javaStr) == pyString
|
|
Comparing Java strings |
javaStr.equals("foo")
|
javaStr == "foo"
|
Checking if Java string |
if (isinstance(obj, JString): ...
|
Arrays
Arrays are create using the JArray class factory. They operate like Python lists, but they are fixed in size.
Description |
Java |
Python |
---|---|---|
Create a single dimension array |
MyClass[] array = new MyClass[5];
|
array = MyClass[5]
|
Create a multi dimension array (old) |
MyClass[][] array2 = new MyClass[5][];
|
array2 = JArray(MyClass, 2)(5)
|
Create a multi dimension array (new) |
MyClass[][] array2 = new MyClass[5][];
|
array2 = MyClass[5,:]
|
Access an element |
array[0] = new MyClass()
|
array[0] = MyClass()
|
Size of an array |
array.length
|
len(array)
|
Get last element |
MyClass a = array[array.length];
|
a = array[-1]
|
Slice an array [18] |
a = array[2:5]
|
|
Clone an array |
MyClass[] a = array.clone();
|
a = array.clone()
|
Convert to Python list |
pylist = list(array)
|
|
Iterate elements |
for (MyClass element: array)
{...}
|
for element in array:
...
|
Checking if java array wrapper |
if (isinstance(obj, JArray): ...
|
Collections
Java standard containers are available and are overloaded with Python syntax where possible to operate in a similar fashion to Python objects.
Description |
Java |
Python |
---|---|---|
Import list type |
import java.util.ArrayList;
|
from java.util import ArrayList
|
Construct a list |
List<Integer> myList=new ArrayList<>();
|
myList=ArrayList()
|
Get length of list |
int sz = myList.size();
|
sz = len(myList)
|
Get list item |
Integer i = myList.get(0)
|
i = myList[0]
|
Set list item [19] |
myList.set(0, 1)
|
myList[0]=Jint(1)
|
Iterate list elements |
for (Integer element: myList)
{...}
|
for element in myList:
...
|
Import map type |
import java.util.HashMap;
|
from java.util import HashMap
|
Construct a map |
Map<String,Integer> myMap = new HashMap<>();
|
myMap = HashMap()
|
Get length of map |
int sz = myMap.size();
|
sz = len(myMap)
|
Get map item |
Integer i = myMap.get("foo")
|
i = myMap["foo"]
|
Set map item [19] |
myMap.set("foo", 1)
|
myMap["foo"] = Jint(1)
|
Iterate map entries |
for (Map.Entry<String,Integer> e
: myMap.entrySet())
{...}
|
for e in myMap.entrySet():
...
|
Reflection
Java reflection can be used to access operations that are outside the scope of the JPype syntax. This includes calling a specific overload or even accessing private methods and fields.
Description |
Java |
Python |
---|---|---|
Access Java reflection class |
MyClass.class
|
MyClass.class_
|
Access a private field by name [20] |
cls = myObject.class_
field = cls.getDeclaredField(
"internalField")
field.setAccessible(True)
field.get()
|
|
Accessing a specific overload [21] |
cls = MyClass.class_
cls.getDeclaredMethod("call", JInt)
cls.invoke(myObject, JInt(1))
|
|
Convert a
|
# Something returned a java.lang.Class
MyClassJava = getClassMethod()
# Convert to it to Python
MyClass = JClass(myClassJava)
|
|
Load a class with a external class loader |
ClassLoader cl
= new ExternalClassLoader();
Class cls
= Class.forName("External",
True, cl)
|
cl = ExternalClassLoader()
cls = JClass("External", loader=cl)
|
Accessing base method implementation |
from org.pkg import \
BaseClass, MyClass
myObject = MyClass(1)
BaseClass.callMember(myObject, 2)
|
Implements and Extension
JPype can implement a Java interface by annotating a Python class. Each method that is required must be implemented.
JPype does not support extending a class directly in Python. Where it is necessary to exend a Java class, it is required to create a Java extension with an interface for each methods that are to be accessed from Python.
Description |
Java |
Python |
---|---|---|
Implement an interface |
public class PyImpl
implements MyInterface
{
public void call()
{...}
}
|
@JImplements(MyInterface)
class PyImpl(object):
@JOverride
def call(self):
pass
|
Extending classes [23] |
None |
|
Lambdas [24] |
DoubleUnaryOperator u = (p->p*2);
|
u=DoubleUnaryOperator@(lambda x: x*2)
|
Don’t like the formatting? Feel the guide is missing something? Submit a pull request at the project page.