2016-02-18 19 views
5

我試圖創建和Jython中投的對象,我收到以下錯誤類轉換異常:Jython的 - 用的PyObject

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經驗的人都可以告訴我我做錯了什麼,我將非常感激。

+1

我不知道'IxNet'和'IxNetType'是什麼樣子。如果這些類型的來源已關閉,您是否可以重寫這些類型以儘量減少其曝光量,但仍然會重現您的問題? –

回答

0

這是一個非常晚的答案,但對於其他人可能面臨同樣的問題:我只是有我認爲是相同的錯誤,並修復它。我猜你的Python類的聲明不會從你的接口繼承。

例如,ixnet.py:

import IxNetType 

class IxNet(IxNetType): 
... 

這是你應該擁有什麼。相反,你可能只是宣佈IxNet爲:

class IxNet: 
... 

這將產生錯誤: 「java.lang.ClassCastException:org.python.core.PySingleton不能轉換到resources.ixia.IxNetType」