pip install JPype1
from jpype import startJVM, shutdownJVM, java
#startJVM(getDefaultJVMPath(), "-ea")
startJVM(convertStrings=False)
java.lang.System.out.println("hello world")
random = java.util.Random()
number1 = random.nextInt(10)
number2 = random.nextInt(10)
print(number1, number2)
shutdownJVM()
See the jpype userguide
I tried this Python 3.7.3 running on Linux.
$ java -version
openjdk version "1.8.0_242"
OpenJDK Runtime Environment (build 1.8.0_242-8u242-b08-0ubuntu3~19.10-b08)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)
$ sudo apt-get install openjdk-8-jdk-headless
$ javac -version
javac 1.8.0_242
examples/python/java1/Calculator.java
public class Calculator {
public static Integer add(Integer a, Integer b) {
return a*b;
}
}
examples/python/java1/org/pkg/MyMath.java
package org.pkg;
public class MyMath {
public static Integer divide(Integer a, Integer b) {
return a/b;
}
}
from jpype import startJVM, shutdownJVM, java, addClassPath, JClass, JInt
startJVM(convertStrings=False)
import jpype.imports
#addClassPath("org/pkg")
#from org.pkg import MyMath
#import MyMath
#import org.pkg as p
#print(p)
#print(p.__class__)
try:
pass
#print(dir(p))
#p.MyMath.divide(6, 2)
#import Calculator
calc = JClass('Calculator')
print(calc)
print(dir(calc))
res = calc.add(java.lang.Integer(2), java.lang.Integer(2))
print(res)
#from org.pkg import Calculator
math = JClass('org.pkg.MyMath')
res = math.divide(java.lang.Integer(6), java.lang.Integer(2))
#res = math.divide(JInt(6), java.lang.Integer(2))
print(res)
#calc = Calculator()
#print(calc)
except Exception as err:
print(f"Exception: {err}")
javac Calculator.java
javac org/pkg/MyMath.java
python calc.py
Directory layout (before running javac):
.
├── calc.py
├── Calculator.java
└── org
└── pkg
└── MyMath.java