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

WBOY
Release: 2016-06-06 11:25:58
Original
1182 people have browsed it

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

Copy after login

上面的代码中,我们使用 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()
Copy after login

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

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!