Jython - 使用PyObject的类转换异常

bil*_*118 5 python java jython

我试图在Jython中创建并转换对象,我收到以下错误:

Exception in thread "MainThread" java.lang.ClassCastException: org.python.core.PySingleton cannot be cast to resources.ixia.IxNetType
at resources.ixia.IxNetFactory.create(IxNetFactory.java:34)
at resources.ixia.IxiaTest.run(IxiaTest.java:34)
at resources.ixia.IxiaTest.<init>(IxiaTest.java:14)
at resources.ixia.IxiaTest.main(IxiaTest.java:42)
Run Code Online (Sandbox Code Playgroud)

这是代码:

import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class IxNetFactory {

    private PyObject ixNetClass;
    private PythonInterpreter interpreter;

    public IxNetFactory(String script_dir) {
        script_dir=script_dir.replace("\\", "/");

        interpreter = new PythonInterpreter();

        interpreter.exec("import sys");             
        interpreter.exec("sys.path.append('"+script_dir+"')");
        interpreter.exec("import time");
        interpreter.exec("import os");
        interpreter.exec("from ixnetworks import IxNet");
        //interpreter.exec("from utils import sm");
        //interpreter.exec("from utils import cpf");

        ixNetClass = interpreter.get("IxNet");
    }

    /*
     * Create an IxNet object
     * 
     * Usage: ixNet.create();
     */
    public IxNetType create() {
        PyObject ixNetObject = ixNetClass.__call__();
        return (IxNetType)ixNetObject.__tojava__(IxNetType.class);
    }

    public void close() {
        interpreter.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我的生活,我无法弄清楚我做错了什么.从我读过的所有内容来看,我似乎正确地做到了这一点,但我无法让它发挥作用.

如果有Jython经验的人能告诉我我做错了什么,我将不胜感激.

Sim*_*tte 0

这是一个很晚的答案,但对于其他可能面临同样问题的人来说:我刚刚遇到了我认为是相同的错误,并修复了它。我猜你的Python类的声明不是从你的接口继承的。

例如,ixnet.py:

import IxNetType

class IxNet(IxNetType):
...
Run Code Online (Sandbox Code Playgroud)

这是你应该拥有的。相反,您可能只是将 IxNet 声明为:

class IxNet:
...
Run Code Online (Sandbox Code Playgroud)

这将产生错误:“java.lang.ClassCastException:org.python.core.PySingleton 无法转换为 resources.ixia.IxNetType”