编程语言
首页 > 编程语言> > Pyjnius — 能让你在Python中轻松调用Java方法

Pyjnius — 能让你在Python中轻松调用Java方法

作者:互联网

1.安装

pip install Cpython

pip install Pyjnius 

2.说明书

https://pyjnius.readthedocs.io

3.使用自定义的类或jar文件

要想使用自定义的class/jar文件必须修改 CLASSPATH环境变量

1.将.class文件打包成jar,然后将CLASSPATH指定jar的路径

import os

os.environ['CLASSPATH'] = '/home/aaron/workspace/javatest.jar'

2.将.class文件路径指向CLASSPATH

import os

os.environ['CLASSPATH'] = '/home/aaron/workspace/JavaTest/bin'

3.通过jnius.config修改CLASSPATH

     import jnius_config

          jnius_config.set_classpath('.','/home/aaron/workspace/JavaTest/bin')

 

from jnius import autoclass

javatest = JavaTest()

javatest.hi()

4.示例

>>> from jnius import autoclass
>>> autoclass('java.lang.System').out.println('Hello world')
Hello world

>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> print(stack.pop())
world
>>> print(stack.pop())
hello

5.进阶

from time import sleep
from jnius import MetaJavaClass, JavaClass, JavaMethod, JavaStaticMethod

class Hardware(JavaClass):
    __metaclass__ = MetaJavaClass
    __javaclass__ = 'org/renpy/android/Hardware'
    vibrate = JavaStaticMethod('(D)V')
    accelerometerEnable = JavaStaticMethod('(Z)V')
    accelerometerReading = JavaStaticMethod('()[F')
    getDPI = JavaStaticMethod('()I')

# 使用这个新类
print('DPI is', Hardware.getDPI())

Hardware.accelerometerEnable()
for x in xrange(20):
    print(Hardware.accelerometerReading())
    sleep(.1)

标签:Java,Python,jnius,CLASSPATH,jar,Hardware,import,Pyjnius,stack
来源: https://www.cnblogs.com/hushaojun/p/15922595.html