本文介绍了通过Jython使用/创建Python对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,

让我说我有一个Java接口B,类似这样. B.java:

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

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

,我想将它与Python类D一起使用,女巫继承了B,就像这样. D.py:

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'

那么现在如何在Java中获取D的实例?很抱歉,我问这样的n00b问题,但是Jython文档很糟糕/部分脱机.

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.

推荐答案

上述示例的代码.您还需要将FooBar实现更改为采用自变量,因为它不是静态方法.

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.

您需要在类路径上有jython.jar才能编译和运行此示例.

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

有关更多信息,请参见 Jython与Java集成中的章节. href ="http://jythonpodcast.hostjava.net/jythonbook/index.html" rel ="nofollow noreferrer"> Jython书

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

这篇关于通过Jython使用/创建Python对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:16