阅读和使用时本文 http://www.rexx.com/~dkuhlman/jython_course_03.html#example-the-jython-classes它假设我们有一个完整的对象定义,包含类和从 python 到 java 的映射(代理)对象。
是否可以仅从 python 中的一段代码导入方法(不在类内部定义,而是使用内部 python 类),而不将其包装在类定义中(不使用上述工厂范例)。
我想做一些from myPyFile import myMethod
来自java,然后使用myMethod,直接来自java(也许作为静态方法?)?但如果这是可能的,我没有找到任何关于如何做到这一点的线索(文章中描述的接口内容可能仍然需要告诉 Java 如何使用 myMethod ?)
此致。
EDIT: 我现在正在处理Jython 2.5.2,所以它可能与版本相关并且将来会更容易?
EDIT :下面回复丹尼尔:
这是一个示例代码,用于重现我收到的错误,并从您有用的回复中获取一个有效的示例!
(好吧,添加一个关于从 a 映射回 Java 对象的其他问题yield-ed Python/Jython 结果)
(@Joonas,抱歉,我修改了我的代码,现在我无法退回到以前的错误)
import org.python.core.Py;
import org.python.core.PyList;
import org.python.core.PyTuple;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
interface MyInterface {
public PyList getSomething(String content, String glue, boolean bool);
}
class MyFactory {
@SuppressWarnings("static-access")
public MyFactory() {
String cmd = "from mymodule import MyClass";
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("C:/jython2.5.2/Lib"));
interpreter.exec(cmd);
jyObjClass = interpreter.get("MyClass");
}
public MyInterface createMe() {
PyObject myObj = jyObjClass.__call__();
return (MyInterface)myObj.__tojava__(MyInterface.class);
}
private PyObject jyObjClass;
}
public class Main {
public static void main(String[] args) {
/*
// with only :
PythonInterpreter interpreter = new PythonInterpreter();
i get :
Exception in thread "main" Traceback (most recent call last):
File "<string>", line 1, in <module>
LookupError: no codec search functions registered: can't find encoding 'iso8859_1'
which is probably due to the :
#!/usr/bin/env python
# -*- coding: latin-1 -*-
// yes i am from France, so my - sorry for that - bad english ;) and have to deal with non 127 ascii chars :)
*/
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("C:/jython2.5.2/Lib"));
interpreter.exec("from mymodule import getSomething");
PyObject tmpFunction = interpreter.get("getSomething");
System.err.println(tmpFunction.getClass());
MyInterface i = (MyInterface) tmpFunction.__tojava__(MyInterface.class);
System.err.println(i.getSomething("test", " - ", true));
for (Object x : i.getSomething("test", " - ", true)) {
System.out.println(x);
// How can i get back an equivallent of the Python _"for (a, b) in getSomething:"_
// with _"a"_ being PyUnicode or better String, and _"b"_ being boolean ?
}
// ^^ so adapting Daniel Teply solution works ! Thanks to him...
// BTW the part below did not work : but i may have missed or/and also mixed many things :/
// i feel Jython damned hard to dive in :/
// and really hope that the sample that i post and answers that i get will help others to swim!
try {
MyFactory factory = new MyFactory();
MyInterface myobj = factory.createMe();
PyList myResult = myobj.getSomething("test", " - ", true);
System.out.println(myResult);
}
catch (Exception e) {
System.out.println(e);
// produce a : java.lang.ClassCastException: org.python.core.PySingleton cannot be cast to MyInterface
// EDIT : see below last edit, this error may be due to my forgotten heritage from interface in the python code!
}
System.exit(-1);
}
}
Python部分:(mymodule.py)
#!/usr/bin/env python
# -*- coding: latin-1 -*-
class MyClass:
def __init__(selfself):
pass
def getSomething(self, content, glue = '', bool = True):
for x in range(5):
yield (glue.join(map(str, (content, x, chr(97 + x))))), bool
#return list()
def getSomething(content, glue = '', bool = True):
print "test"
myclass = MyClass()
return list(myclass.getSomething(content, glue, bool))
def main():
test()
if __name__ == "__main__":
main()
EDIT :
对于内部问题(内部评论),部分回答我自己:
(实际上我觉得我的答案和代码很丑陋,但它有效并且似乎可以取消-tuple我不知道是否有更好的 Jythonic 方式来做到这一点,如果有的话,我真的很感兴趣:))
for (Object x : i.getSomething("test", " - ", true)) {
System.out.println(x);
// How can i get back an equivallent of the Python _"for (a, b) in getSomething:"_
// with _"a"_ being PyUnicode or better String, and _"b"_ being boolean ?
// answering myself here :
PyTuple mytuple = (PyTuple) x; // casting back x as PyTuple, can we have a java equivalent to _`(a, b) = x_ ? not sure...
PyObject a = mytuple.__getitem__(0);
PyObject b = mytuple.__getitem__(1);
String aS = a.toString(); // mapping a unicode python string to java is as simple?
boolean bB = b.toString().toLowerCase().equals("true");
System.out.println(mytuple + "[" + aS + "][" + b + "][" + bB + "]");
EDIT:
回答我自己关于“产生一个:“java.lang.ClassCastException:org.python.core.PySingleton 无法转换为 MyInterface”...我的大部分误解和错误都是由于我忘记了从Python部分处理Java! (参见上面的代码,我对这个事实没有进行更正,因为这不是我的主要问题,而在其实际形式中,这是关于这个主要问题的有效答案,非常感谢丹尼尔和乔纳斯帮助我理解)。因此对于工厂范式,我们应该NOT忘记将足够的导入添加到其 Python 文件中:
from testjython.interfaces import MyInterface #// defining method inside a MyInterface.java
class MyClass(MyInterface):
[...]
我遇到的另一个困难是正确处理导入和包。
顺便说一句,将此代码添加到上面的代码中将产生一个类型错误:无法转换为 org.python.core.PyList但这是另一个问题......