如何通过Jython将Java List传入Python函数?含报错求助
Got it, let's sort out this issue you're facing with passing a Java ArrayList to a Python function using Jython. That IllegalArgumentException pops up because directly creating a PyList from a raw Java ArrayList doesn't properly convert the Java elements into Python-compatible objects—Jython needs explicit type mapping between Java and Python types here.
The Root Cause
When you use new PyList(new ArrayList<>()), Jython doesn't automatically convert each element in the Java list to a corresponding PyObject subtype. This leads to a mismatch between the expected array type ([Lorg.python.core.PyObject;) and the unprocessed Java elements.
Solution: Properly Convert Java ArrayList to PyList
Jython provides a built-in method to handle this conversion cleanly, or you can manually map elements if you need custom logic. Here are both approaches:
1. Use PyList.fromJavaList() (Recommended)
This method is designed specifically to convert Java List instances to Jython PyList, automatically handling basic type conversions (like Integer → PyInteger, String → PyString):
// Initialize your Java ArrayList with actual elements ArrayList<Object> javaArrayList = new ArrayList<>(); // Add your elements here, e.g.: // javaArrayList.add(42); // javaArrayList.add("sample string"); // Convert Java ArrayList to PyList correctly PyList pyList = PyList.fromJavaList(javaArrayList); // Rest of your existing code remains mostly the same PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile(getClass().getResourceAsStream("/com/ppts/propertiesfiles/sample_return_script.py")); PyObject function = interpreter.get("returnSample"); PyObject result = function.__call__(new PyInteger(1), pyList, new PyDictionary()); progress = (int) result.__tojava__(Integer.class);
2. Manual Element Conversion (For Custom Logic)
If you need to handle non-standard types or add custom conversion logic, iterate over the Java list and convert each element explicitly:
ArrayList<Object> javaArrayList = new ArrayList<>(); // Populate your list with elements PyList pyList = new PyList(); for (Object item : javaArrayList) { // Map Java types to corresponding Jython types if (item instanceof Integer) { pyList.add(new PyInteger((Integer) item)); } else if (item instanceof String) { pyList.add(new PyString((String) item)); } else if (item instanceof Boolean) { pyList.add(new PyBoolean((Boolean) item)); } // Add more type checks based on your actual element types } // Proceed with executing the Python function as before
Why This Works
Both approaches ensure that every element in the list is converted to a PyObject subtype (like PyInteger, PyString), which matches the array type Jython expects. This eliminates the type mismatch that was causing your original error.
内容的提问来源于stack exchange,提问作者eThan_hunT

