Using/Creating Python objects with Jython

半腔热情 提交于 2019-12-24 01:38:42

问题


HI,

lets say I have a Java interface B, something like this. B.java :

public interface B { String FooBar(String s); }

and I want to use it with a Python class D witch inherits B, like this. D.py :

class D(B):
    def FooBar(s)
        return s + 'e'

So now how do I get an instance of D in java? I'm sorry im asking such a n00b question but the Jython doc sucks / is partially off line.


回答1:


Code for your example above. You also need to change the FooBar implementation to take a self argument since it is not a static method.

You need to have jython.jar on the classpath for this example to compile and run.

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class Main {

    public static B create() 
    {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("from D import D");
        PyObject DClass = interpreter.get("D");

        PyObject DObject = DClass.__call__();
        return (B)DObject.__tojava__(B.class);
    }

    public static void main(String[] args) 
    {
        B b = create();
        System.out.println(b.FooBar("Wall-"));
    }
}

For more info see the chapter on Jython and Java integration in the Jython Book



来源:https://stackoverflow.com/questions/1582674/using-creating-python-objects-with-jython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!