欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-04-12 08:53:02|栏目:Python代码|点击:
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中获取。

上一篇:如何高效使用Python字典的方法详解

栏    目:Python代码

下一篇:python hmac模块验证客户端的合法性

本文标题:从Python程序中访问Java类的简单示例

本文地址:http://www.codeinn.net/misctech/99589.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有