1. 程式人生 > 實用技巧 >pyjnius:訪問java類

pyjnius:訪問java類

簡介

Pyjnius是一個用於訪問Java類的Python庫。

適用場景:極個別的加密演算法等內容,用python不方便實現或者實現較耗時,可基於Pyjnius把java類當做python庫使用。

注意jnius的版本管理有點混亂,目前看來選擇jniusx比較好。

安裝

先安裝Java JDK 和JRE、Cython

# pip3 install cython

# pip3 install jniusx

Collecting jniusx

  Downloading jniusx-1.0.5.tar.gz

Requirement already satisfied: six>=1.7.0 in /opt/python3.5/lib/python3.5/site-packages (from jniusx)

Requirement already satisfied: cython in /opt/python3.5/lib/python3.5/site-packages (from
jniusx) Installing collected packages: jniusx Running setup.py install for jniusx ... done Successfully installed jniusx-1.0.5

注意:jnius安裝的坑比較多,請參考http://stackoverflow.com/search?q=jnius

如果出現ImportError,一般是java環境變數或者path沒有配置好。

jnius/jnius.c:4:20: fatal error: Python.h 一般為缺python-dev, yum -y install python-devel

pip 安裝不成功可以嘗試 setup.py方式。

jnius/jnius.c: No such file or directory 需要利用原來儲存的clone。

快速入門

hello world 例項:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# jnius_quick2.py

# Author Rongzhong Xu 2016-08-02 wechat: pythontesting

# https://bitbucket.org/china-testing/python-chinese-library/src

"""

jnius demo

Tested in python2.7 

"""

from jnius import autoclass

System = autoclass('java.lang.System')

System.out.println('Hello World')

堆疊例項:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# jnius_quick1.py

# Author Rongzhong Xu 2016-08-02 wechat: pythontesting

# https://bitbucket.org/china-testing/python-chinese-library/src

"""

jnius demo

Tested in python2.7 

"""

from jnius import autoclass

Stack = autoclass('java.util.Stack')

stack = Stack()

stack.push('hello')

stack.push('world')

print(stack.pop())  # --> 'world'

print(stack.pop())  # --> 'hello'

呼叫java String的hashCode

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# jnius_quick3.py

# Author Rongzhong Xu 2016-08-02 wechat: pythontesting

# https://bitbucket.org/china-testing/python-chinese-library/src

"""

jnius demo: Call java String's hashCode

Tested in python2.7 

"""

from jnius import autoclass

String = autoclass('java.lang.String')

print(String("hello").hashCode())

呼叫jar包

#!python

# vi com/sample/Beach.java 

package com.sample;

public class Beach {

    private String name;

    private String city;

    public Beach(String name, String city){

        this.name = name;

        this.city = city;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getCity() {

        return city;

    }

    public void setCity(String city) {

        this.city = city;

    }

}

# echo Main-Class: Beach >manifest.txt

# jar cvfm Test.jar manifest.txt com/sample/*.class

測試:

#!python

# ipython

Python 3.5.2 (default, Nov  7 2016, 18:53:51) 

Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.

?        -> Introduction and overview of IPython's features.

%quickref -> Quick reference.

help      -> Python's own help system.

object?  -> Details about 'object', use 'object??' for extra details.

In [2]: # 注意要先把jar載入CLASSPATH環境變數。

In [3]: from jnius import autoclass

In [4]: Bla = autoclass('com.sample.Beach')

In [5]: s = Bla("Tom", "Shenzhen")

In [6]: s.getName()

Out[6]: 'Tom'

```

封裝某模組的加密機制為python包例項:

* 拷貝: com cn org 到新建的臨時目錄

* echo Main-Class: AESUtil >manifest.txt

* jar cvfm Test.jar manifest.txt *

測試程式碼:

```python

# -*- coding: utf-8 -*-

# 注意要先把jar載入CLASSPATH環境變數。

from jnius import autoclass

AESUtil = autoclass('com.oppo.sso.util.AESUtil')

email = AESUtil.aesEncrypt("[email protected]","我是一個加密金鑰")

print(email)

注意:以上打包方式和具體環境很相關,建議儘量本機打包,本機執行。