2017-07-31 54 views
1

我想爲Java方法提供一個Python函數作爲消費者。Java消費者的Jython函數

public Class MyObject { 
    public void javaFunction(Consumer<Double> consumer){...} 
} 

def python_function(arg): 
    some_code_using(arg) 

我試過如下:

myObjectInstance.javaFunction(python_function) 

myObjectInstance.javaFunction(lambda arg: python_function(arg)) 

每一次,我得到1日ARG不能被強制到Java .util.function.Consumer

我以前用供應商做過這件事,它運行良好。我正在使用org.python.util.PythonInterpreter

有關如何通過此類消費者的任何想法?

回答

0

@suvy一個在從this answer提示可以創建設置助手的歸類,像這樣

from java.util.Arrays import asList 
from java.util.function import Predicate, Consumer, Function 
from java.util.stream import Collectors 

class jc(Consumer): 
    def __init__(self, fn): 
     self.accept=fn 

class jf(Function): 
    def __init__(self, fn): 
     self.apply = fn 

class jp(Predicate): 
    def __init__(self, fn): 
     self.test = fn 

,後來可以用像這樣

>>> def p(x): 
...  print(x) 
... 
>>> asList("one", "two", "three").stream().filter(jp(lambda x: len(x)>3)).map(jf(lambda x: "a"+x)).forEach(jc(lambda x: p("foo"+x))).collect(Collectors.toList()) 
fooathree 

,或者使用內置Collectors類,如果你需要收集結果

>>> asList("one", "two", "three").stream().filter(jp(lambda x: len(x)>3)).map(jf(lambda x: "a"+x)).collect(Collectors.toList()) 
[athree]