Although Jython is primarily known for enabling Java calls from Python scripts, it also has the capability to bridge the gap in the opposite direction.
Jython acts as a bridge that allows Java applications to seamlessly invoke Python functions. To achieve this:
To illustrate how Python functions can be called from Java using Jython, consider the following example:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// Calling a Python function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);
It's important to note that as of 2021, Jython does not support Python 3.x. Therefore, ensure that your Python code meets these limitations for successful integration with Java.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3