html tool

2017年9月28日星期四

jython 运行java code

http://willzh.iteye.com/blog/307222


1. 用Jython调用Java类库 

第一步、创建Java类 

写一个简单的Java类,用Point来示例: 
Java代码  收藏代码
  1. import org.python.core.*;  
  2.   
  3. public class Point extends PyObject  
  4. {  
  5.     private int x;  
  6.     private int y;  
  7.   
  8.     public Point()  
  9.     {  
  10.         x = 0;  
  11.         y = 0;  
  12.     }  
  13.   
  14.     public Point(int x, int y)  
  15.     {  
  16.         this.x = x;  
  17.         this.y = y;  
  18.     }  
  19.   
  20.     public void dump()  
  21.     {  
  22.         System.out.printf("The position is (%s, %s)\n", x , y);  
  23.     }  
  24. }  

编译的时候,记得把jython.jar加入类环境中: 
Shell代码  收藏代码
  1. export CLASSPATH=/usr/share/java/jython.jar  
  2. javac Point.java  


第二步、简单调用 

现在可以编写Jython来调用上面的Java类库了 在shell中运行 jython point.py 就可以了
Jython代码  收藏代码
  1. #!/usr/bin/env jython  
  2.   
  3. import Point  
  4.   
  5. if __name__ == "__main__":  
  6.     p = Point(2,3)  
  7.     p.dump()  

没有评论:

发表评论