通过 Jython 使用/创建 Python 对象

发布于 2024-08-07 21:09:53 字数 322 浏览 3 评论 0原文

嗨,

假设我有一个 Java 接口 B,类似这样。 B.java :

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

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

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

那么现在如何在 java 中获取 D 的实例?很抱歉我问了这样一个 n00b 问题,但 Jython 文档很糟糕/部分离线。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亢潮 2024-08-14 21:09:53

上面示例的代码。您还需要更改 FooBar 实现以采用 self 参数,因为它不是静态方法。

您需要在类路径中包含 jython.jar 才能编译和运行此示例。

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 集成 中的章节http://jythonpodcast.hostjava.net/jythonbook/index.html" rel="nofollow noreferrer">Jython 图书

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文