@@ -92,11 +92,11 @@ set the class path, start the JVM, remove all the type declarations, and you are
92
92
93
93
# Copy in the patterns from the guide to replace the example code
94
94
db = Database(" our_records" )
95
- with db.connect() as DatabaseConnection:
96
- c.runQuery()
97
- while c.hasRecords():
98
- record = db.nextRecord()
99
- ...
95
+ with db.connect() as DatabaseConnection:
96
+ c.runQuery()
97
+ while c.hasRecords():
98
+ record = db.nextRecord()
99
+ ...
100
100
101
101
Launch it in the interactive window. You can get back to programming in Python
102
102
once you get a good night sleep.
@@ -136,11 +136,11 @@ in your serialized object.
136
136
from java.nio.file import Files, Paths
137
137
from java.io import ObjectInputStream
138
138
139
- with Files.newInputStream(Paths.get(" myobject.ser" ) as stream:
140
- ois = new ObjectInputStream(stream)
141
- obj = ois.readObject()
139
+ with Files.newInputStream(Paths.get(" myobject.ser" )) as stream:
140
+ ois = ObjectInputStream(stream)
141
+ obj = ois.readObject()
142
142
143
- print (obj) # prints org.bigstuff.MyObject@7382f612
143
+ print (obj) # prints org.bigstuff.MyObject@7382f612
144
144
145
145
It appears that the structure is loaded. The problematic structure requires you
146
146
call the getData method with the correct index.
@@ -172,7 +172,7 @@ example and watch what happens.
172
172
173
173
.. code-block :: python
174
174
175
- import matplot .pyplot as plt
175
+ import matplotlib .pyplot as plt
176
176
plt.plot(d)
177
177
plt.show()
178
178
@@ -227,13 +227,13 @@ Based on the previous examples, you start by defining a monitor class
227
227
228
228
@JImplements (Monitor)
229
229
class HeartMonitor :
230
- def __init__ (self ):
231
- self .readings = []
232
- @ JOverride
233
- def onMeasurement(self , measurement):
234
- self .readings.append([measurement.getTime(), measurement.getHeartRate()])
235
- def getResults(self ):
236
- return np.array(self .readings)
230
+ def __init__ (self ):
231
+ self .readings = []
232
+ @JOverride
233
+ def onMeasurement (self , measurement ):
234
+ self .readings.append([measurement.getTime(), measurement.getHeartRate()])
235
+ def getResults (self ):
236
+ return np.array(self .readings)
237
237
238
238
There is a bit to unpack here. You have implemented a Java class from within Python.
239
239
The Java implementation is simply an ordinary Python class which has be
@@ -762,7 +762,7 @@ entirely the domain of whatever JPype has defined including user defined casts.
762
762
As `` JObject`` syntax is long and does not look much like Java syntax, the
763
763
Python matmul operator is overloaded on JPype types such that one can use the
764
764
`` @ `` operator to cast to a specific Java type . In Java, one would write
765
- `` (Type)@ object `` to cast the variable `` object `` to `` Type`` . In Python, this
765
+ `` (Type)object `` to cast the variable `` object `` to `` Type`` . In Python, this
766
766
would be written as `` Type@ object `` . This can also be applied to array types
767
767
`` JLong[:]@ [1 ,2 ,3 ]`` , collection types `` Iterable@ [1 ,2 ,3 ]`` or Java functors
768
768
`` DoubleUnaryOperator@ (lambda x :x* 2 )`` . The result of the casting operator
@@ -1656,28 +1656,28 @@ Here is an example:
1656
1656
.. code- block:: python
1657
1657
1658
1658
try :
1659
- # Code that throws a java.lang.RuntimeException
1659
+ # Code that throws a java.lang.RuntimeException
1660
1660
except java.lang.RuntimeException as ex:
1661
- print (" Caught the runtime exception : " , str (ex))
1662
- print (ex.stacktrace())
1661
+ print (" Caught the runtime exception : " , str (ex))
1662
+ print (ex.stacktrace())
1663
1663
1664
1664
Multiple java exceptions can be caught together or separately:
1665
1665
1666
1666
.. code- block:: python
1667
1667
1668
1668
try :
1669
- # ...
1669
+ # ...
1670
1670
except (java.lang.ClassCastException, java.lang.NullPointerException) as ex:
1671
- print (" Caught multiple exceptions : " , str (ex))
1672
- print (ex.stacktrace())
1671
+ print (" Caught multiple exceptions : " , str (ex))
1672
+ print (ex.stacktrace())
1673
1673
except java.lang.RuntimeException as ex:
1674
- print (" Caught runtime exception : " , str (ex))
1675
- print (ex.stacktrace())
1676
- except jpype.JException:
1677
- print (" Caught base exception : " , str (ex))
1678
- print (ex.stacktrace())
1674
+ print (" Caught runtime exception : " , str (ex))
1675
+ print (ex.stacktrace())
1676
+ except jpype.JException as ex :
1677
+ print (" Caught base exception : " , str (ex))
1678
+ print (ex.stacktrace())
1679
1679
except Exception as ex:
1680
- print (" Caught python exception :" , str (ex))
1680
+ print (" Caught python exception :" , str (ex))
1681
1681
1682
1682
Exceptions can be raised in proxies to throw an exception back to Java.
1683
1683
@@ -1903,7 +1903,7 @@ should be attached to the Java Runtime object. The following pattern is used:
1903
1903
class MyShutdownHook:
1904
1904
@ JOverride
1905
1905
def run(self ):
1906
- # perform any required shutdown activities
1906
+ # perform any required shutdown activities
1907
1907
1908
1908
java.lang.Runtime.getRuntime().addShutdownHook(Thread(MyShutdownHook()))
1909
1909
@@ -1975,16 +1975,16 @@ Example taken from JPype ``java.util.Map`` customizer:
1975
1975
@ _jcustomizer.JImplementationFor(' java.util.Map' )
1976
1976
class _JMap:
1977
1977
def __jclass_init__(self ):
1978
- Mapping.register(self )
1978
+ Mapping.register(self )
1979
1979
1980
1980
def __len__ (self ):
1981
- return self .size()
1981
+ return self .size()
1982
1982
1983
1983
def __iter__ (self ):
1984
- return self .keySet().iterator()
1984
+ return self .keySet().iterator()
1985
1985
1986
1986
def __delitem__ (self , i):
1987
- return self .remove(i)
1987
+ return self .remove(i)
1988
1988
1989
1989
1990
1990
The name of the class does not matter for the purposes of customizer though it
@@ -2355,19 +2355,19 @@ dispatch:
2355
2355
2356
2356
@ JImplements(JavaInterface)
2357
2357
class MyImpl:
2358
- @ JOverride
2359
- def callOverloaded(self , * args):
2360
- # always use the wild card args when implementing a dispatch
2361
- if len (args)== 2 :
2362
- return self .callMethod1(* args)
2363
- if len (args)== 1 and isinstance (args[0 ], JString):
2364
- return self .callMethod2(* args)
2365
- raise RuntimeError (" Incorrect arguments" )
2358
+ @ JOverride
2359
+ def callOverloaded(self , * args):
2360
+ # always use the wild card args when implementing a dispatch
2361
+ if len (args)== 2 :
2362
+ return self .callMethod1(* args)
2363
+ if len (args)== 1 and isinstance (args[0 ], JString):
2364
+ return self .callMethod2(* args)
2365
+ raise RuntimeError (" Incorrect arguments" )
2366
2366
2367
2367
def callMethod1(self , a1, a2):
2368
- # ...
2368
+ # ...
2369
2369
def callMethod2(self , jstr):
2370
- # ...
2370
+ # ...
2371
2371
2372
2372
Multiple interfaces
2373
2373
------------------ -
@@ -2388,7 +2388,7 @@ achieve this, specify the interface using a string and add the keyword argument
2388
2388
2389
2389
@ JImplements(" org.foo.JavaInterface" , deferred = True )
2390
2390
class MyImpl:
2391
- # ...
2391
+ # ...
2392
2392
2393
2393
2394
2394
Deferred proxies are not checked at declaration time, but instead at the time
@@ -2444,27 +2444,27 @@ First, with an object:
2444
2444
2445
2445
.. code- block:: python
2446
2446
2447
- class C :
2448
- def testMethod(self ) :
2449
- return 42
2447
+ class C:
2448
+ def testMethod(self ):
2449
+ return 42
2450
2450
2451
- def testMethod2(self ) :
2452
- return " Bar"
2451
+ def testMethod2(self ):
2452
+ return " Bar"
2453
2453
2454
2454
c = C() # create an instance
2455
- proxy = JProxy(" ITestInterface2" , inst = c) # Convert it into a proxy
2455
+ proxy = JProxy(" ITestInterface2" , inst = c) # Convert it into a proxy
2456
2456
2457
2457
or you can use a dictionary.
2458
2458
2459
2459
.. code- block:: python
2460
2460
2461
- def _testMethod() :
2462
- return 32
2461
+ def _testMethod():
2462
+ return 32
2463
2463
2464
- def _testMethod2() :
2465
- return " Fooo!"
2464
+ def _testMethod2():
2465
+ return " Fooo!"
2466
2466
2467
- d = { ' testMethod' : _testMethod, ' testMethod2' : _testMethod2, }
2467
+ d = { ' testMethod' : _testMethod, ' testMethod2' : _testMethod2, }
2468
2468
proxy = JProxy(" ITestInterface2" , dict = d)
2469
2469
2470
2470
@@ -2548,19 +2548,19 @@ launches it from within Python.
2548
2548
from javax.swing import *
2549
2549
2550
2550
def createAndShowGUI():
2551
- frame = JFrame(" HelloWorldSwing" )
2552
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE )
2553
- label = JLabel(" Hello World" )
2554
- frame.getContentPane().add(label)
2555
- frame.pack()
2556
- frame.setVisible(True )
2551
+ frame = JFrame(" HelloWorldSwing" )
2552
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE )
2553
+ label = JLabel(" Hello World" )
2554
+ frame.getContentPane().add(label)
2555
+ frame.pack()
2556
+ frame.setVisible(True )
2557
2557
2558
2558
# Start an event loop thread to handling gui events
2559
2559
@ jpype.JImplements(java.lang.Runnable)
2560
2560
class Launch:
2561
- @ jpype.JOverride
2562
- def run(self ):
2563
- createAndShowGUI()
2561
+ @ jpype.JOverride
2562
+ def run(self ):
2563
+ createAndShowGUI()
2564
2564
javax.swing.SwingUtilities.invokeLater(Launch())
2565
2565
2566
2566
@@ -2658,12 +2658,12 @@ keep the synchronization on as long as the object is kept alive. For example,
2658
2658
mySharedList = java.util.ArrayList()
2659
2659
2660
2660
# Give the list to another thread that will be adding items
2661
- otherThread, setList(mySharedList)
2661
+ otherThread. setList(mySharedList)
2662
2662
2663
2663
# Lock the list so that we can access it without interference
2664
2664
with synchronized(mySharedList):
2665
- if not mySharedList.isEmpty():
2666
- ... # process elements
2665
+ if not mySharedList.isEmpty():
2666
+ ... # process elements
2667
2667
# Resource is unlocked once we leave the block
2668
2668
2669
2669
The Python `` with `` statement is used to control the scope. Do not
@@ -2695,26 +2695,26 @@ results. For example:
2695
2695
2696
2696
.. code- block:: python
2697
2697
2698
- def limit(method, timeout):
2699
- """ Convert a Java method to asynchronous call with a specified timeout. """
2700
- def f(* args):
2701
- @ jpype.JImplements(java.util.concurrent.Callable)
2702
- class g:
2703
- @ jpype.JOverride
2704
- def call(self ):
2705
- return method(* args)
2706
- future = java.util.concurrent.FutureTask(g())
2707
- java.lang.Thread(future).start()
2708
- try :
2709
- timeunit = java.util.concurrent.TimeUnit.MILLISECONDS
2710
- return future.get(int (timeout* 1000 ), timeunit)
2711
- except java.util.concurrent.TimeoutException as ex:
2712
- future.cancel(True )
2713
- raise RuntimeError (" canceled" , ex)
2714
- return f
2715
-
2716
- print (limit(java.lang.Thread.sleep, timeout = 1 )(200 ))
2717
- print (limit(java.lang.Thread.sleep, timeout = 1 )(20000 ))
2698
+ def limit(method, timeout):
2699
+ """ Convert a Java method to asynchronous call with a specified timeout. """
2700
+ def f(* args):
2701
+ @ jpype.JImplements(java.util.concurrent.Callable)
2702
+ class g:
2703
+ @ jpype.JOverride
2704
+ def call(self ):
2705
+ return method(* args)
2706
+ future = java.util.concurrent.FutureTask(g())
2707
+ java.lang.Thread(future).start()
2708
+ try :
2709
+ timeunit = java.util.concurrent.TimeUnit.MILLISECONDS
2710
+ return future.get(int (timeout* 1000 ), timeunit)
2711
+ except java.util.concurrent.TimeoutException as ex:
2712
+ future.cancel(True )
2713
+ raise RuntimeError (" canceled" , ex)
2714
+ return f
2715
+
2716
+ print (limit(java.lang.Thread.sleep, timeout = 1 )(200 ))
2717
+ print (limit(java.lang.Thread.sleep, timeout = 1 )(20000 ))
2718
2718
2719
2719
Here we have limited the execution time of a Java call.
2720
2720
@@ -3268,7 +3268,7 @@ this block as a fixture at the start of the test suite.
3268
3268
faulthandler.enable()
3269
3269
faulthandler.disable()
3270
3270
except :
3271
- pass
3271
+ pass
3272
3272
3273
3273
This code enables fault handling and then returns the default handlers which
3274
3274
will point back to those set by Java.
0 commit comments