2017-07-31 56 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]