Home  >  Article  >  Backend Development  >  从Python程序中访问Java类的简单示例

从Python程序中访问Java类的简单示例

WBOY
WBOYOriginal
2016-06-06 11:25:581092browse

from jnius import autoclass
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> stack.pop()
'world'
>>> stack.pop()
'hello'

上面的代码中,我们使用 autoclass 函数,创建了一个类型代理,对应着Java中java.util.Stack类的所有方法和字段属性。

OK,也许你想要一个Android相关的例子,看这里:

from jnius import autoclass
from time import sleep
 
MediaRecorder = autoclass('android.media.MediaRecorder')
AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')
 
# Record the Microphone with a 3GP recorder
mRecorder = MediaRecorder()
mRecorder.setAudioSource(AudioSource.MIC)
mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
mRecorder.setOutputFile('/sdcard/testrecorder.3gp')
mRecorder.setAudioEncoder(AudioEncoder.ARM_NB)
mRecorder.prepare()
 
# Record 5 seconds
mRecorder.start()
sleep(5)
mRecorder.stop()
mRecorder.release()

好了,你可以从文档中获取更多的例子。

我们已经可以映射Java/Python的类型,原生数组,支持方法重载等等。我们在内部使用的是 Cython + JNI,因此消耗性能是最小的。

同时, Python for android库已经完成,你可以从github中获取。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn