python call java code

Description:  Python as a flexible software development languages are widely used today. In the software development process, and sometimes we need to use existing Java code in the Python project, has the purpose of saving time and development costs. Thus, finding a Python code to call Java code bridge is very significant. JPype is one such tool, which allows you to make Python programs easily call Java code to expand the capacity of the Python language, make up the Python language. This article describes some basic ways how JPype integrate Python and Java programs.

Overview:

JPype is a python code that allows easily call Java code tool to overcome the lack of python in certain areas (such as server-side programming) in.

Jdk installed first and the third party package and jpype python is a 64-bit or 32-bit.

Prerequisites: jdk and python are already installed

Related methods in python virtual machine operations:

Start JVM

The role of JPype provided startJVM () function is to start the JAVA virtual machine, so before any subsequent JAVA code is called, you must call this method to start the JAVA virtual machine.

jpype.startJVM () is defined

 

startJVM (JVM, * args)

# Jpype.startJVM () parameter 
# 1 parameter: jvm, describe a path jvm.dll your system files are located, such as "C: \ Program Files \ IBM \ Java50 \ jre \ bin \ j9vm \ jvm.dll". Can be obtained by calling the default JVM path jpype.getDefaultJVMPath (). 
# Parameter 2: args, optional parameters are passed directly to JPype JVM as a Java virtual machine startup parameters. Here for all legal JVM startup parameters, such as 
 -agentlib: libname [= Options] 
  - the CLASSPATH the CLASSPATH 
  - verbose 
  -Xint

 

jpype.startJVM () Usage Example

 

import jpype 
 jvmPath = jpype.getDefaultJVMPath() 
 jvmArg = “ -Xint ”
 jpype.startJVM (jvmPath, jvmArg)

 

Determine whether to start the JVM

The role of JPype provided jpype.isJVMStarted () function is to determine whether the JVM is started.

  • jpype.isJVMStarted () is defined

isJVMStarted()

  • jpype.isJVMStarted () Returns the value of

The return value is True to the JVM has started, the return value of False indicates JVM has not started

# Jpype.isJVMStarted () usage example 
Import JPype
 jvmPath = jpype.getDefaultJVMPath() 
 jvmArg = “ -Xint ”
 if not jpype.isJVMStarted(): 
    jpype.startJVM (jvmPath, jvmArg)

 Close JVM

When finished using the JVM, can be closed by a JVM jpype.shutdownJVM (), the function has no input parameters. When the python program exits, JVM will automatically shut down.

 

Call a way: write java code directly in python code, call the java api

Here is a simple python program, by calling Java JPype print function, print out the string.

import jpype 
 jvmPath = jpype.getDefaultJVMPath() 
 jpype.startJVM (jvmPath) 
 jpype.java.lang.System.out.println( “ hello world! ” ) 
 jpype.shutdownJVM()

Call way: call java class files (.class file)

Here we use a simple application example to illustrate how to call Java classes in python code.

Suppose we have written a class in the Java language: PasswordCipher, this kind of function is to encrypt and decrypt strings. It provides an interface to run an outbound () function is defined as follows:

public class PasswordCipher { 
    ……
    public static String run(String action, String para){ 
    ……
    } 
……
 }

run function accepts two parameters, a first parameter representing the operation to be performed, the incoming "encrypt" representation of the second parameter para do encryption, returns the encrypted result. If the first parameter is "decrypt" the result of the decryption operation is returned para. It is possible to run the function will throw an exception.

We first PasswordCipher.class stored in the directory: under "F \ test \ cipher", and then write the following code in python language:

Python code

 

import jpype 
 from jpype import JavaException 

 jvmPath = jpype.getDefaultJVMPath()           #the path of jvm.dll 
 classpath = "F:\\test\\cipher"                 #the path of PasswordCipher.class 
 jvmArg = "-Djava.class.path=" + classpath 
 if not jpype.isJVMStarted():                    #test whether the JVM is started 
    jpype.startJVM (jvmPath, jvmArg) #start JVM 
 javaClass = jpype.JClass("PasswordCipher")   #create the Java class 
 try: 
    testString = "congratulations" 
    print "original string is : ", testString 
    #call the run function of Java class 
    encryptedString = javaClass.run("encrypt", testString) 
    print "encrypted string is : ", encryptedString 

    #call the run function of Java class 

    decryptedString = javaClass.run("decrypt", encryptedString) 
    print "decryped string is : ", decryptedString 
 except JavaException, ex: 
    print "Caught exception : ", JavaException.message() 
    print JavaException.stackTrace() 
 except: 
    print "Unknown Error" 
 finally: 
    jpype.shutdownJVM()        #shut down JVM 

After running the program to get results:

 

original string is :  congratulations 
 encrypted string is :  B0CL+niNYwJLgx/9tisAcQ== 
 decryped string is :  congratulations

 

 

Three ways to call: Call the third party jar package

step 1 to install jpype

pip install jpype1

step 2 write java code

package mainpro;

public class Hello {
    public void sh(){
        System.out.println("I am sh method");
    }
    public static void show() {
        System.out.println("I am show() method");
    }
    public static void main(String[] args) {
        System.out.println("hello , I am coming");
        Hello.show();
        Hello hello = new Hello();
        hello.sh();

    }
}

 

step 3 jar packaging

jartest.jar

step 4 develop python program

# -*- coding: utf-8 -*-
import jpype
import os

if __name__ == '__main__':
    """
    Basic development process is as follows:
    ①, using jpype open jvm
    ②, loading java class
    ③, calling java method
    ④, closed (closed not in the true sense, unload loaded before the class) jvm
    """

    # ①, using a virtual machine jpype open (to open before loading the classpath JVM) 
    # loaded just packaged jar file 
    jarpath the os.path.join = (os.path.abspath with ( ' . ' ), ' D: / tmp / jartest.jar ' )

    # Get file path jvm.dll of 
    jvmPath = jpype.getDefaultJVMPath ()

    # Open JVM 
    jpype.startJVM (jvmPath, ' -ea ' , ' -Djava.class.path% S = ' % (jarpath))
     # loading java class (parameter name is long java class name) 
    javaClass jpype.JClass = ( ' mainpro.Hello ' )

    # Instantiate java objects 
    javaInstance = javaClass ()

    # Instantiation call the method 
    javaInstance.sh ()
     # The Book of Songs with class calls the static method 
    javaClass.show ()
     # can not call the main method directly! ! ! ! ! ! ! ? ? 
    # JavaClass.main ()
    
    # Close the JVM 
    jpype.shutdownJVM ()

Guess you like

Origin www.cnblogs.com/yoyowin/p/12130937.html