PyLucene JCC:在python中实现Java接口并通过它接收Java线程回调

时间:2015-01-12 13:17:21

标签: java python python-2.7 pylucene jcc

我正在玩我的新玩具JCC 2.21,并且在使用python脚本实现回调时遇到了麻烦。我已经包装了以下简单的Java线程API并从python 2.7(CPython)调用它,但是当我调用JccTest.addJccTestListener(JccTestListener)方法时,JVM报告一个空参数。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class JccTest implements Runnable {

    private final Object listenersLock = new Object();
    private final List<JccTestListener> listeners = new ArrayList<JccTestListener>();
    private final AtomicBoolean running = new AtomicBoolean(false);
    private final AtomicBoolean finished = new AtomicBoolean(false);

    public void start() {
        if (running.compareAndSet(false, true)) {            
            new Thread(this).start();
        }
    }

    public void stop() {
        finished.set(true);
    }

    public void addJccTestListener(JccTestListener l) {
        if (l == null) {
            throw new IllegalArgumentException("argument must be non-null");
        }
        synchronized (listenersLock) {
            listeners.add(l);
        }
    }

    public void removeJccTestListener(JccTestListener l) {
        synchronized (listenersLock) {
            listeners.remove(l);
        }
    }

    @Override
    public void run() {     
        System.out.println("Start");

        while (!finished.get()) {
            System.out.println("Notifiying listeners");
            synchronized (listenersLock) {
                for (JccTestListener l : listeners) {
                    System.out.println("Notifiying " + String.valueOf(l));
                    l.message("I'm giving you a message!");
                }
            }
            System.out.println("Sleeping");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                continue;
            }
        }

        running.set(false);
        System.out.println("Stop");
    }

    public static void main(String[] args) throws InterruptedException {
        JccTest test = new JccTest();
        test.addJccTestListener(new JccTestListener() {

            @Override
            public void message(String msg) {
                // called from another thread
                System.out.println(msg);
            }
        });
        test.start();
        Thread.sleep(10000);
        test.stop();
    }
}

public interface JccTestListener {
    public void message(String msg);
}

生成的包装器:

python -m jcc --jar jcc-test.jar --python jcc_test --build --install

然后执行此脚本(相当于JccTest的主要方法):

import jcc_test
import time, sys

jcc_test.initVM(jcc_test.CLASSPATH)

test = jcc_test.JccTest()


class MyListener(jcc_test.JccTestListener):
    def __init__(self):
        pass

    def message(self, msg):
        print msg

test.addJccTestListener(MyListener())
test.start()
time.sleep(10)
test.stop()

sys.exit(0)

结果是:

"python.exe" jcc_test_test.py
Traceback (most recent call last):
  File "jcc_test_test.py", line 16, in <module>
    test.addJccTestListener(MyListener())
jcc_test.JavaError: java.lang.IllegalArgumentException: argument must be non-null
    Java stacktrace:
java.lang.IllegalArgumentException: argument must be non-null
    at com.example.jcc.JccTest.addJccTestListener(JccTest.java:32)

除了null侦听器实例之外,CPython甚至可以做这样的事情吗?我已经读过,在它的实现中,一次只有一个线程可以执行python脚本,这可能(?)对我来说是一个问题。用Jython做这样的事情是微不足道的。

我对python很新,所以请保持温和。

1 个答案:

答案 0 :(得分:0)

想出来。您需要为java类定义pythonic扩展以使其工作。详细过程在JCC documentation在Python中编写Java类扩展)中描述,并且非常简单。

首先,编写一个实现接口的类,并添加一些JCC识别的魔术标记,并影响包装器生成器将生成的内容。

public class JccTestListenerImpl implements JccTestListener {

    // jcc specific
    private long pythonObject;

    public JccTestListenerImpl() {}

    @Override
    public void message(String msg) {
        messageImpl(msg);
    }

    // jcc specific
    public void pythonExtension(long pythonObject) {
        this.pythonObject = pythonObject;
    }

    // jcc specific
    public long pythonExtension() {
        return this.pythonObject;
    }

    // jcc specific
    @Override
    public void finalize() throws Throwable {
        pythonDecRef();
    }

    // jcc specific
    public native void pythonDecRef();

    public native void messageImpl(String msg);

}

标记由我的注释表示,并且必须逐字逐句显示在要在python中扩展的任何类中。我的实现将接口方法委托给本机实现方法,该方法将在python中进行扩展。

然后像往常一样生成包装器:

python -m jcc --jar jcc-test.jar --python jcc_test --build --install

最后为新类做一个python扩展:

import jcc_test
import time, sys

jvm = jcc_test.initVM(jcc_test.CLASSPATH)

test = jcc_test.JccTest()


class MyListener(jcc_test.JccTestListenerImpl):
    ## if you define a constructor here make sure to invoke super constructor
    #def __init__(self):
    #    super(MyListener, self).__init__()
    #    pass

    def messageImpl(self, msg):
        print msg


listener = MyListener()
test.addJccTestListener(listener)
test.start()
time.sleep(10)
test.stop()

sys.exit(0)

这现在可以正常运行回调。

"python.exe" jcc_test_test.py
Start
Notifiying listeners
Notifiying com.example.jcc.JccTestListenerImpl@4b67cf4d
I'm giving you a message!
Sleeping
Notifiying listeners
Notifiying com.example.jcc.JccTestListenerImpl@4b67cf4d
I'm giving you a message!
Sleeping

Process finished with exit code 0