Learning Python -- Java 通过JyThon调用Python实现的规则

学习Python的时候,发现Java能够通过JyThon调用 Python 脚本。那么也可以使用Python实现判断逻辑,像规则一样,Java实现具体行为。

例子:

Java 行为部分

Java 接口

package sample;
public interface Fruit {

    public String getName();
    public String getType();
    public void show();
}

对以上接口的2个实现类

package sample;
public class Apple implements Fruit {

    public String getName(){
        return "java apple";
    }
    public String getType(){
        return "apple";
    }
    
    public void show(){
        System.out.println("Show: I am a java apple.");
    }
}
package sample;
public class Orange implements Fruit {

    public String getName(){
        return "java orange";
    }
    public String getType(){
        return "orange";
    }
    
    public void show(){
        System.out.println("Show: I am a java orange.");
    }
}

下面是Python部分。

1 、Python实现java接口的方式:

用于Python的Java 接口

package sample;

public interface GroovyController {

    public void controllFruit(Fruit fruit);
}
Python的实现,另存为文件(PythonClass.py),文件扩展名为 .py
from java.lang import String
from sample import GroovyController
from sample import Fruit

class PythonClass(GroovyController):

     # If the method does not include the parameter "self" and 
     # the parameter is not in first place , something wrong will happen
     def controllFruit( self, fruit ):
        fruit.show()
        if fruit.getType() == "apple" :
            print ("disk Python apple")

        if fruit.getType() == "orange" :
            print ("disk Python orange")

        print ("END")
     
# single founction
def functionControllFruit( fruit ):
        fruit.show()
        if fruit.getType() == "apple" :
            print ("function disk Python apple")

        if fruit.getType() == "orange" :
            print ("function disk Python orange")

        print (" function END")
     
2、Python Script的方式
Python Script: 另存为文件(PythonScript.py)

from java.lang import String
from sample import Fruit

fruit.show()
if fruit.getType() == "apple" :
    print ("script function disk Python apple")

if fruit.getType() == "orange" :
    print ("script function disk Python orange")

print ("script function END")
     
Java 调用以上2种 Python 的例子

package sample;
import java.io.File;
import java.io.IOException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.io.FileUtils;
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;


public class JythonManager {

    public static void testJavaInvokePython(){
        String pythonPath = "d:/PythonClass.py";
        String javaInterfaceName = "sample.GroovyController";
        String pythonInstanceName = "pythonController";
        String pythonClassName = "PythonClass";
        Fruit apple = new Apple();
        Fruit orange = new Orange();
        PythonInterpreter interpreter = null;
        // Java Object way
        System.out.println("Java Object way");
        interpreter = new PythonInterpreter();
        interpreter.execfile(pythonPath);
        interpreter.exec(pythonInstanceName + "=" + pythonClassName + "()"); // Create a python object in python script
        try {
            Class JavaInterface = Class.forName(javaInterfaceName);
            
            GroovyController controller = 
                    (GroovyController)interpreter.get(pythonInstanceName).__tojava__(GroovyController.class);
            controller.controllFruit(apple);
            controller.controllFruit(orange);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        
        System.out.println("Java Object way end");
        System.out.println("-------------------------------------------------");
        System.out.println("Python Object way");
        
        interpreter = new PythonInterpreter();
        interpreter.execfile(pythonPath);
        interpreter.exec(pythonInstanceName + "=" + pythonClassName + "()"); // Create a python object in python script
        
        PyObject pyObject = interpreter.get(pythonInstanceName);
        pyObject.invoke("controllFruit", Py.java2py(apple));
        pyObject.invoke("controllFruit", Py.java2py(orange));
                
        System.out.println("Python Object way end");
        System.out.println("-------------------------------------------------");
        System.out.println("Python function way");
        
        interpreter = new PythonInterpreter();
        interpreter.execfile(pythonPath);
        
        PyFunction pyFunction = interpreter.get("functionControllFruit", PyFunction.class);
        pyFunction.__call__(Py.java2py(apple));
        pyFunction.__call__(Py.java2py(orange));
        
        System.out.println("Python function way end");
        System.out.println("-------------------------------------------------");
        System.out.println("Python script way");
        
        String scriptText = null;
        try {
            scriptText = FileUtils.readFileToString(new File("d:/PythonScript.py"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

        try {
            engine.put("fruit", apple);
            engine.eval(scriptText);
            
            engine.put("fruit", orange);
            engine.eval(scriptText);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        System.out.println("Python script way end");
        
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        testJavaInvokePython();
    }
}
结果

Java Object way
Show: I am a java apple.
disk Python apple
END
Show: I am a java orange.
disk Python orange
END
Java Object way end
-------------------------------------------------
Python Object way
Show: I am a java apple.
disk Python apple
END
Show: I am a java orange.
disk Python orange
END
Python Object way end
-------------------------------------------------
Python function way
Show: I am a java apple.
function disk Python apple
 function END
Show: I am a java orange.
function disk Python orange
 function END
Python function way end
-------------------------------------------------
Python script way
Show: I am a java apple.
script function disk Python apple
script function END
Show: I am a java orange.
script function disk Python orange
script function END
Python script way end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值