Debian Codegraph @

doc/reference.rst

raw
1 #########
2 Reference
3 #########
4
5
6 **********
7 Python API
8 **********
9
10
11 This reference addresses the jpy Python module.
12
13 jpy Functions
14 =============
15
16 .. py:function:: create_jvm(options)
17 :module: jpy
18
19 Create the Java VM using the given *options* sequence of strings. Possible option strings are of the form:
20
21 +-------------------------------+------------------------------------------------------------------------------------------------------------------------+
22 | Option | Meaning |
23 +===============================+========================================================================================================================+
24 | ``-D<name>=<value>`` | Set a `Java system property <http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties%28%29>`_. |
25 | | The most important system property is ``java.class.path`` to include your Java libraries. You may also consider |
26 | | ``java.library.path`` if your Java code uses native code provided in shared libraries. |
27 +-------------------------------+------------------------------------------------------------------------------------------------------------------------+
28 | ``-verbose[:class|gc|jni]`` | Enable verbose output. The options can be followed by a comma-separated list |
29 | | of names indicating what kind of messages will be printed by the JVM. |
30 | | For example, ``-verbose:gc,class`` instructs the JVM to print GC and class |
31 | | loading related messages. Standard names include: gc, class, and jni. |
32 +-------------------------------+------------------------------------------------------------------------------------------------------------------------+
33 | ``-X<value>`` | Set a non-standard JVM option which usually begins with ``-X`` or an underscore. For example, |
34 | | the Oracle JDK/JRE supports ``-Xms`` and ``-Xmx`` options to allow programmers specify the initial |
35 | | and maximum heap size. Please refer to the documentation of the used Java Runtime Environment (JRE). |
36 +-------------------------------+------------------------------------------------------------------------------------------------------------------------+
37
38 The function throws a runtime error on failure. It has no return value.
39
40 Usage example::
41
42 jpy.create_jvm(['-Xmx512M', '-Djava.class.path=/usr/home/norman/jpy-test/classes'])
43
44
45
46 .. py:function:: destroy_jvm()
47 :module: jpy
48
49 Destroy the Java Virtual Machine. The function has no effect if the JVM is has not yet been created or has already
50 been destroyed. No return value.
51
52
53 .. py:function:: get_type(name, resolve=False)
54 :module: jpy
55
56 Return a type object for the given, fully qualified Java type *name* which is the name of a Java primitive type,
57 a Java class name, or a Java array type name.
58
59 Java class names must be fully qualified, e.g. ``'java.awt.Point'``. For inner classes a dollar sign is
60 used to separate it from its containing class, e.g. ``'java.awt.geom.Ellipse2D$Float'``.
61
62 Java array type names have a trailing opening bracket, followed by either a Java class name and a trailing semicolon
63 or followed by one of the primitive type indicators:
64
65 * ``'Z'``, the Java ``boolean`` type (an 8-bit Boolean value)
66 * ``'C'``, Java ``char`` type (a 16-bit unicode character)
67 * ``'B'``, Java ``byte`` type (an 8-bit signed integer number)
68 * ``'S'``, Java ``short`` type (a 16-bit signed integer number)
69 * ``'I'``, Java ``int`` type (a 32-bit signed integer number)
70 * ``'J'``, Java ``long`` type (a 64-bit signed integer number)
71 * ``'F'``, Java ``float`` type (a 32-bit floating point number)
72 * ``'D'``, Java ``double`` type (a 64-bit floating point number)
73
74 Examples: ``'[java.awt.Point;'`` (1d object array), ``'[[[F'`` (3d float array).
75
76 If the returned Java type has public constructors it can be used to create Java object instances in the same way
77 Python objects are created from their types, e.g.::
78
79 String = jpy.get_type('java.lang.String')
80 s = String(‘Hello jpy!’)
81 s = s.substring(0, 5)
82
83 The returned Java types are also used to access the type's static fields and methods::
84
85 Runtime = jpy.get_type('java.lang.Runtime')
86 rt = Runtime.getRuntime()
87 tm = rt.totalMemory()
88
89 The returned Java types have a `jclass` attribute which returns the actual Java object. This allows for using
90 the Java types where a Java method would expect a parameter of type `java.lang.Class`. They also have a `jclassname`
91 attribute, which returns the Java type associated with the 'obj' reference. The `jclassname` is the reference's
92 declared type (which may be a supertype), rather than the object's runtime type (as returned by
93 `obj.getClass().getName()`).
94
95 To instantiate Java array objects, the :py:func:`jpy.array()` function is used.
96
97 Implementation note: All types loaded so far from the Java VM are stored in the global :py:data:`jpy.types` variable.
98 If the requested type does not already exists in :py:data:`jpy.types`, the class is newly loaded from the Java VM.
99 The root class of all Java types retrieved that way is :py:class:`jpy.JType`.
100
101 Make sure that :py:func:`jpy.create_jvm()` has already been called. Otherwise the function fails with a runtime
102 exception.
103
104
105 .. py:function:: array(item_type, init)
106 :module: jpy
107
108 Create a Java array object for the given *item_type* and of the given initializer *init*.
109
110 *item_type* may be a *type* object as returned by the :py:func:`jpy.get_type()` function or a type *name* as it is
111 used for the :py:func:`jpy.get_type()` function. In addition, the name of a Java primitive type can be used:
112
113 * ``'boolean'`` (an 8-bit Boolean value)
114 * ``'char'`` (a 16-bit unicode character)
115 * ``'byte'`` (an 8-bit signed integer number)
116 * ``'short'`` (a 16-bit signed integer number)
117 * ``'int'`` (a 32-bit signed integer number)
118 * ``'long'`` (a 64-bit signed integer number)
119 * ``'float'`` (a 32-bit floating point number)
120 * ``'double'`` (a 64-bit floating point number)
121
122 The value for the *init* parameter may bei either an array length in the range ``0`` to ``2**31-1`` or a sequence
123 of objects which all must be convertible to the given *item_type*.
124
125 Make sure that :py:func:`jpy.create_jvm()` has already been called. Otherwise the function fails with a runtime
126 exception.
127
128 Examples:::
129
130 a = jpy.array('java.lang.String', ['A', 'B', 'C'])
131 a = jpy.array('int', [1, 2, 3])
132 a = jpy.array('float', 512)
133
134
135
136 .. py:function:: cast(jobj, type)
137 :module: jpy
138
139 Convert a Java object to a Java object with the given Java *type* (type object or type name, see
140 :py:func:`jpy.get_type()`). If *jobj* is already of *type*, *jobj* is returned. If *jobj* is an instance of
141 *type*, a new wrapper object will be created for this type, otherwise ``None`` is returned.
142
143 This function is useful if you need to convert the `java.util.Object` values returned e.g. by Java collections
144 (implementations of the `java.util.Set`, `java.util.Map`, `java.util.List` & Co.) to specific types. For example::
145
146 ArrayList = jpy.get_type('java.util.ArrayList')
147 File = jpy.get_type('java.io.File')
148 al = ArrayList()
149 al.add(File('/home/bibo/.jpy'))
150 item = al.get(0)
151 # item has type java.util.Object, but actually is a java.io.File
152 print(type(item))
153 item = jpy.cast(item, File)
154 # item has now type java.io.File
155 print(type(item))
156
157 Make sure that :py:func:`jpy.create_jvm()` has already been called. Otherwise the function fails with a runtime
158 exception.
159
160 Variables
161 =========
162
163 .. py:data:: types
164 :module: jpy
165
166 A dictionary that maps Java class names to the respective Python type objects (wrapped Java classes).
167 You should never modify the value of this variable nor directly modify the dictionary's contents.
168
169 .. py:data:: type_callbacks
170 :module: jpy
171
172 Contains callbacks which are called before jpy translates Java methods to Python methods while Java classes are
173 being loaded. These callbacks can be used to annotate Java methods so that jpy can better translate them to
174 Python. This is a powerful but advanced jpy feature that you usually don't have to use.
175
176 Consider a Java method::
177
178 double[] readData(long offset, int length, double[] data);
179
180 of some Java class ``Reader``. From the method's documentation we know that if we pass ``null`` for *data*,
181 it will create a new array of the given length, read data into it and the return that instance.
182 If we pass an existing array it will be reused instead. From plain Java class introspection, jpy can neither
183 detect if a primitive array parameter is modified by a method and/or whether it shall serve as the method's
184 return value.
185
186 To overcome the problem of such semantics inherent to a Java method implementation, jpy uses a dictionary
187 ``type_callbacks`` in which you can register a Java class name with a callable of following signature: ::
188
189 callback(type, method)
190
191 This can be used to equip specific Java methods of a class with additional information while the Java class
192 is being loaded from the Java VM. *type* is the Java class and *method* is the current class method being
193 loaded. *method* is of type :py:class:`jpy.JMethod`. The callback should return either ``True`` or ``False``.
194 If it returns ``False``, jpy will not add the given method to the Python version of the Java class.
195
196 Here is an example: ::
197
198 def annotate_Reader_readData_methods(type, method):
199 if method.name == 'readData' and method.param_count == 3:
200 param_type_str = str(method.get_param_type(1))
201 if param_type_str == "<class '[I'>" || param_type_str == "<class '[D'>":
202 method.set_param_mutable(2, True)
203 method.set_param_return(2, True)
204 return True
205
206 class_name = 'com.acme.Reader'
207 jpy.type_callbacks[class_name] = annotate_Reader_readData_methods
208 # This will invoke the callback above
209 Reader = jpy.get_type(class_name)
210
211 Once a method parameter is annotated that way, jpy can transfer the semantics of a Java method to Python.
212 For example::
213
214 import numpy as np
215
216 r = Reader('test.tif')
217 a = np.array(1024, np.dtype=np.float64)
218 a = r.read(0, len(a), a)
219 r.close()
220
221 Here a call to the ``read`` method will modify the numpy array's content as desired and return the
222 same array instance as indicated by the Java method's specification.
223
224 .. py:data:: type_translations
225 :module: jpy
226
227 Contains callbacks which are called when instantiating a Python object from a Java object.
228 After the standard wrapping of the Java object as a Python object, the Java type name is looked up in this
229 dictionary. If the returned item is a callable, the callable is called with the JPy object as an argument,
230 and the callable's result is returned to the user.
231
232
233 .. py:data:: VerboseExceptions.enabled
234 :module: jpy
235
236 If set to true, then jpy will produce more verbose exception messages; which include the full Java stack trace.
237 If set to false, then jpy produces exceptions using only the underlying Java exception's toString method.
238
239 .. py:data:: diag
240 :module: jpy
241
242 An object used to control output of diagnostic information for debugging. This variable is only useful for jpy
243 modification and further development.
244
245 .. py:data:: diag.flags
246 :module: jpy
247
248 Integer bit-combination of diagnostic flags (see following F_* constants).
249 If this value is not zero, diagnostic messages are printed to the standard output stream for any subsequent
250 jpy library calls. Its default value is ``jpy.diag.F_OFF`` which is zero.
251
252 For example::
253
254 jpy.diag.flags = jpy.diag.F_EXEC + jpy.diag.F_JVM
255
256 The following flags are defined:
257
258 * ``F_OFF`` - Don't print any diagnostic messages
259 * ``F_ERR`` - Errors: print diagnostic information when erroneous states are detected
260 * ``F_TYPE`` - Type resolution: print diagnostic messages while generating Python classes from Java classes
261 * ``F_METH`` - Method resolution: print diagnostic messages while resolving Java overloaded methods
262 * ``F_EXEC`` - Execution: print diagnostic messages when Java code is executed
263 * ``F_MEM`` - Memory: print diagnostic messages when wrapped Java objects are allocated/deallocated
264 * ``F_JVM`` - JVM: print diagnostic information usage of the Java VM Invocation API
265 * ``F_ALL`` - Print all possible diagnostic messages
266
267
268 Types
269 =====
270
271 You will never have to use the following type directly. But it may be of use to know where they come from when they are
272 referred to, e.g. in error messages.
273
274 .. py:class:: JType
275 :module: jpy
276
277 This type is the base class for all type representing Java classes. It is actually a meta-type used to dynamically
278 create Python type instances from loaded Java classes. Such derived types are returned by
279 :py:func:`jpy.get_type` instead or can be directly looked up in :py:data:`jpy.types`.
280
281
282 .. py:class:: JOverloadedMethod
283 :module: jpy
284
285 This type represents an overloaded Java method. It is composed of one or more :py:class:`jpy.JMethod` objects.
286
287
288 .. py:class:: JMethod
289 :module: jpy
290
291 This type represents a Java method. It is part of a :py:class:`jpy.JOverloadedMethod`.
292
293 .. py:attribute:: name
294
295 The method's name. Read-only attribute.
296
297 .. py:attribute:: return_type
298
299 The method's return type. Read-only attribute.
300
301 .. py:attribute:: param_count
302
303 The method's parameter count. Read-only attribute.
304
305 .. py:method:: JMethod.get_param_type(i) -> type
306
307 Get the type of the *i*-th Java method parameter.
308
309 .. py:method:: JMethod.is_param_return(i) -> bool
310
311 Return ``True`` if arguments passed to the *i*-th Java method parameter will be the return value of the method, ``False`` otherwise.
312
313 .. py:method:: JMethod.set_param_return(i, value)
314
315 Set if arguments passed to the *i*-th Java method parameter will be the return value of the method, with *value* being a Boolean.
316
317 .. py:method:: JMethod.is_param_output(i) -> bool
318
319 Return ``True`` if the arguments passed to the *i*-th Java method parameter is a mere output (and not read from), ``False`` otherwise.
320
321 .. py:method:: JMethod.set_param_output(i, value)
322
323 Set if arguments passed to the *i*-th Java method parameter is a mere output (and not read from), with *value* being a Boolean.
324 Used to optimise Python buffer to Java array parameter passing.
325
326 .. py:method:: JMethod.is_param_mutable(i) -> bool
327
328 Return ``True`` if the arguments passed to the *i*-th Java method parameter is mutable, ``False`` otherwise.
329
330 .. py:method:: JMethod.set_param_mutable(i, value)
331
332 Set if arguments passed to the *i*-th Java method parameter is mutable, with *value* being a Boolean.
333
334
335 .. py:class:: JField
336 :module: jpy
337
338 This type represents is used to represent Java class fields.
339
340
341 Type Conversions
342 ================
343
344 This section describes the type possible type conversions made by jpy when Python values are passed as arguments
345 to Java typed parameters. In the tables given below are the generated match values ranging from (types never match)
346 to 100 (full match) when comparing a given Java parameter type (rows) with a provided Python value (columns). These
347 match values are also used for finding the best matching Java method overload for a given Python argument tuple.
348
349
350 Java primitive types
351 --------------------
352
353
354 +--------------+--------------+----------+---------+------------+--------+
355 | | ``NoneType`` | ``bool`` | ``int`` | ``float`` | number |
356 +==============+==============+==========+=========+============+========+
357 | ``boolean`` | 1 | 100 | 10 | 0 | 0 |
358 +--------------+--------------+----------+---------+------------+--------+
359 | ``char`` | 0 | 10 | 100 | 0 | 0 |
360 +--------------+--------------+----------+---------+------------+--------+
361 | ``byte`` | 0 | 10 | 100 | 0 | 0 |
362 +--------------+--------------+----------+---------+------------+--------+
363 | ``short`` | 0 | 10 | 100 | 0 | 0 |
364 +--------------+--------------+----------+---------+------------+--------+
365 | ``int`` | 0 | 10 | 100 | 0 | 0 |
366 +--------------+--------------+----------+---------+------------+--------+
367 | ``long`` | 0 | 10 | 100 | 0 | 0 |
368 +--------------+--------------+----------+---------+------------+--------+
369 | ``float`` | 0 | 1 | 10 | 90 | 50 |
370 +--------------+--------------+----------+---------+------------+--------+
371 | ``double`` | 0 | 1 | 10 | 100 | 50 |
372 +--------------+--------------+----------+---------+------------+--------+
373
374 Java object types
375 -----------------
376
377 +-------------------------+--------------+----------+---------+------------+---------+
378 | | ``NoneType`` | ``bool`` | ``int`` | ``float`` | ``str`` |
379 +=========================+==============+==========+=========+============+=========+
380 | ``java.lang.Boolean`` | 1 | 100 | 10 | 0 | 0 |
381 +-------------------------+--------------+----------+---------+------------+---------+
382 | ``java.lang.Character`` | 1 | 10 | 100 | 0 | 0 |
383 +-------------------------+--------------+----------+---------+------------+---------+
384 | ``java.lang.Byte`` | 1 | 10 | 100 | 0 | 0 |
385 +-------------------------+--------------+----------+---------+------------+---------+
386 | ``java.lang.Short`` | 1 | 10 | 100 | 0 | 0 |
387 +-------------------------+--------------+----------+---------+------------+---------+
388 | ``java.lang.Integer`` | 1 | 10 | 100 | 0 | 0 |
389 +-------------------------+--------------+----------+---------+------------+---------+
390 | ``java.lang.Long`` | 1 | 10 | 100 | 0 | 0 |
391 +-------------------------+--------------+----------+---------+------------+---------+
392 | ``java.lang.Float`` | 1 | 1 | 10 | 90 | 0 |
393 +-------------------------+--------------+----------+---------+------------+---------+
394 | ``java.lang.Double`` | 1 | 1 | 10 | 100 | 0 |
395 +-------------------------+--------------+----------+---------+------------+---------+
396 | ``java.lang.String`` | 1 | 0 | 0 | 0 | 100 |
397 +-------------------------+--------------+----------+---------+------------+---------+
398 | ``java.lang.Object`` | 1 | 10 | 10 | 10 | 10 |
399 +-------------------------+--------------+----------+---------+------------+---------+jpy
400
401 Java primitive array types
402 --------------------------
403
404 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
405 | | ``NoneType`` | seq | buf('b') | buf('B') | buf('u') | buf('h') | buf('H') | buf('i') | buf('I') | buf('l') | buf('L') | buf('q') | buf('Q') | buf('f') | buf('d') |
406 +================+==============+=====+==========+==========+==========+==========+==========+==========+==========+==========+==========+==========+==========+==========+==========+
407 | ``boolean[]`` | 1 | 10 | 100 | 100 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
408 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
409 | ``char[]`` | 1 | 10 | 0 | 0 | 100 | 80 | 90 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
410 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
411 | ``byte[]`` | 1 | 10 | 100 | 90 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
412 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
413 | ``short[]`` | 1 | 10 | 0 | 0 | 0 | 100 | 90 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
414 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
415 | ``int[]`` | 1 | 10 | 0 | 0 | 0 | 0 | 0 | 100 | 90 | 100 | 90 | 0 | 0 | 0 | 0 |
416 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
417 | ``long[]`` | 1 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 100 | 90 | 0 | 0 |
418 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
419 | ``float[]`` | 1 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 100 | 0 |
420 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
421 | ``double[]`` | 1 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 100 |
422 +----------------+--------------+-----+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
423
424 If a python buffer is passed as argument to a primitive array parameter, but it doesn't match the buffer types
425 given above, the a match value of 10 applies, as long as the item size of a buffer matches the Java array item size.
426
427 Java object array types
428 -----------------------
429
430 For String arrays, if a sequence is matched with a value of 80 if all the elements in the sequence are Python strings.
431
432
433 todo
434
435
436
437 ********
438 Java API
439 ********
440
441 jpy's Java API documentation has been generated from Java source code using the javadoc tool.
442 It can be found `here <_static/java-apidocs/index.html>`_.