【问题标题】:Jython - Class Cast Exception with PyObjectJython - PyObject 的类转换异常
【发布时间】:2016-05-31 05:12:48
【问题描述】:

我正在尝试在 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)

代码如下:

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();
    }
}

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

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

【问题讨论】:

  • 我想知道IxNetIxNetType 是什么样子的。如果这些类型的来源已关闭,您是否可以重写它们以最大限度地减少它们的暴露但仍然重现您的问题?

标签: java python jython


【解决方案1】:

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

例如ixnet.py:

import IxNetType

class IxNet(IxNetType):
...

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

class IxNet:
...

会产生错误:“java.lang.ClassCastException: org.python.core.PySingleton cannot be cast to resources.ixia.IxNetType”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多