add cast(classname, obj) method to be able to use an instance from another class def

This commit is contained in:
Mathieu Virbel 2012-08-16 00:16:17 +02:00
parent 7eecc34237
commit 774fc295e9
4 changed files with 29 additions and 3 deletions

View File

@ -1,4 +1,4 @@
from .jnius import (JavaObject, JavaMethod, JavaStaticMethod, from .jnius import (JavaObject, JavaMethod, JavaStaticMethod,
JavaField, JavaStaticField, JavaClass, MetaJavaClass, JavaField, JavaStaticField, JavaClass, MetaJavaClass,
JavaException) JavaException, cast)

View File

@ -86,7 +86,7 @@ Python::
''' '''
__all__ = ('JavaObject', 'JavaClass', 'JavaMethod', 'JavaStaticMethod', __all__ = ('JavaObject', 'JavaClass', 'JavaMethod', 'JavaStaticMethod',
'JavaField', 'JavaStaticField', 'MetaJavaClass', 'JavaException') 'JavaField', 'JavaStaticField', 'MetaJavaClass', 'JavaException', 'cast')
from libc.stdlib cimport malloc, free from libc.stdlib cimport malloc, free
@ -895,3 +895,15 @@ cdef class JavaMethodMultiple(object):
jm.j_self = self.j_self jm.j_self = self.j_self
return jm.__call__(*args) return jm.__call__(*args)
def cast(destclass, obj):
cdef JavaClass jc
cdef JavaClass jobj = obj
from reflect import autoclass
if isinstance(destclass, basestring):
jc = autoclass(destclass)(noinstance=True)
else:
jc = destclass(noinstance=True)
jc.instanciate_from(jobj.j_self)
return jc

View File

@ -1,3 +1,5 @@
__all__ = ('autoclass', 'ensureclass')
from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, \ from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, \
JavaField, JavaStaticField, JavaMethodMultiple JavaField, JavaStaticField, JavaMethodMultiple
@ -169,4 +171,3 @@ def autoclass(clsname):
clsname,#.replace('.', '_'), clsname,#.replace('.', '_'),
(JavaClass, ), (JavaClass, ),
classDict) classDict)

13
tests/test_cast.py Normal file
View File

@ -0,0 +1,13 @@
import unittest
from jnius.reflect import autoclass
from jnius import cast
class MultipleSignature(unittest.TestCase):
def test_multiple_constructors(self):
String = autoclass('java.lang.String')
s = String('hello world')
self.assertEquals(s.__javaclass__, 'java/lang/String')
o = cast('java.lang.Object', s)
self.assertEquals(o.__javaclass__, 'java/lang/Object')