Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Python and Java

Python and Java

Jython

Calling Java from Python

Jython - Python running on the JVM

Jython Installation

  • java

  • jython

  • Jython

  • java -jar jython-installer-2.7.0.jar

  • ~/jython2.7.0/

Jython Installation

java -jar ~/jython2.7.0/jython.jar

java -jar ~/jython2.7.0/jython.jar some.py

Jython load Java class

cd examples/mymath/
java -jar ~/jython2.7.0/jython.jar
Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_60
Type "help", "copyright", "credits" or "license" for more information.
>>> import Calculator
>>> Calculator.add(2, 3)
5
>>> Calculator.add(10, 3)
10
>>>

Jython load Java class in code

public class Calculator {
    public static Integer add(Integer a, Integer b) {
        if (a == 10) {
            return 10;
        }
        return a+b;
    }

}

# use only with Jython

import Calculator
print(Calculator.add(4, 8))
print(Calculator.add(10, 8))

cd examples/jython/mymath/
java -jar ~/jython2.7.0/jython.jar calc.py

Jython test Java class

import unittest
import Calculator

class TestAdd(unittest.TestCase):

    def test_add(self):
        self.assertEqual(Calculator.add(4, 8), 12)
        self.assertEqual(Calculator.add(10, 8), 18)
        self.assertEqual(Calculator.add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()
 
java -jar ~/jython2.7.0/jython.jar calc.py
java -jar ~/jython2.7.0/jython.jar -m unittest discover