diff --git a/jnius/__init__.py b/jnius/__init__.py index b120418..5386691 100644 --- a/jnius/__init__.py +++ b/jnius/__init__.py @@ -1,4 +1,4 @@ from .jnius import (JavaObject, JavaMethod, JavaStaticMethod, JavaField, JavaStaticField, JavaClass, MetaJavaClass, - JavaException) + JavaException, cast) diff --git a/jnius/jnius.pyx b/jnius/jnius.pyx index f9fad64..0ae397f 100644 --- a/jnius/jnius.pyx +++ b/jnius/jnius.pyx @@ -86,7 +86,7 @@ Python:: ''' __all__ = ('JavaObject', 'JavaClass', 'JavaMethod', 'JavaStaticMethod', - 'JavaField', 'JavaStaticField', 'MetaJavaClass', 'JavaException') + 'JavaField', 'JavaStaticField', 'MetaJavaClass', 'JavaException', 'cast') from libc.stdlib cimport malloc, free @@ -895,3 +895,15 @@ cdef class JavaMethodMultiple(object): jm.j_self = self.j_self 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 + diff --git a/jnius/reflect.py b/jnius/reflect.py index 7bf514b..e5c2099 100644 --- a/jnius/reflect.py +++ b/jnius/reflect.py @@ -1,3 +1,5 @@ +__all__ = ('autoclass', 'ensureclass') + from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, \ JavaField, JavaStaticField, JavaMethodMultiple @@ -169,4 +171,3 @@ def autoclass(clsname): clsname,#.replace('.', '_'), (JavaClass, ), classDict) - diff --git a/tests/test_cast.py b/tests/test_cast.py new file mode 100644 index 0000000..ef33746 --- /dev/null +++ b/tests/test_cast.py @@ -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') +