Jython与Java的互相调用
上一篇 /
下一篇 2008-03-09 23:00:10
一.在Java中调用Jython 主要是调用这个类org.python.util.PythonInterpreter的使用方法。 这里给出Jython给的一个例子: import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args)throws PyException { PythonInterpreter interp = new PythonInterpreter();
System.out.println("Hello, brave new world"); interp.exec("import sys"); interp.exec("print sys");
interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x");
System.out.println("x: "+x); System.out.println("Goodbye, cruel world"); }
二.在Jython中操作Java 使Python能够简单的使用现有的Java库是Jython的一个目标。 例子: 在Jython的交互式的环境中,如何使用Jython建立一个Java下的随机数类的实例(java.util.Random)和使用这个实例。 C:\jython>jython Jython 2.0 on java1.2.1 Type "copyright", "credits" or "license" for more information. >>> from java.util import Random >>> r = Random() >>> r.nextInt() -790940041 >>> for i in range(5): ... print r.nextDouble() ... 0.23347681506123852 0.8526595592189546 0.3647833839988137 0.3384865260567278 0.5514469740469587 >>>
其它内容 在这个例子中展示了在Jython环境中使用Java包和Python库的差异很小,但是仍然有一些需要注意的事情。 Importing Jython 2.0 on java1.2.1 Type "copyright", "credits" or "license" for more information. >>> from java.util import * >>> Random <jclass java.util.Random at 31702169> >>> Hashtable <jclass java.util.Hashtable at 7538094> >>> 建立类的实例 可以用建立Python类实例的方法建立起Java的类实例,你必须调用带有参数“Java类名”,这些参数必须和Java类的构造函数相适应。下面将更详细的介绍关于参数的内容。 调用Java方法和函数 Java classes have both static and instance methods this makes them
behave much like a cross between a Python module and class. As a user,
you should rarely need to be concerned with this difference. 调用Java的方法和函数就象调用这些方法的Python副本一样。方法的输入参数类型和返回值的类型被自动强制转换。这个表显示Python对象作为方
法的输入参数如何转换为java对象的。注意如果java.lang.Object 输入参数预期为一个String时,在置换时有问题。
|