Jython与Java的互相调用

一.在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

>>> Hashtable

>>>

建立类的实例
可以用建立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时,在置换时有问题。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/13186779/viewspace-201860/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/13186779/viewspace-201860/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值