mirror of https://github.com/kivy/pyjnius.git
Merge pull request #271 from InvalidCo/list_getitem_indexerror
for...in iteration of list interfaces
This commit is contained in:
commit
efe610b89d
|
@ -7,7 +7,8 @@ from six import with_metaclass
|
|||
|
||||
from .jnius import (
|
||||
JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod,
|
||||
JavaField, JavaStaticField, JavaMultipleMethod, find_javaclass
|
||||
JavaField, JavaStaticField, JavaMultipleMethod, find_javaclass,
|
||||
JavaException
|
||||
)
|
||||
|
||||
|
||||
|
@ -218,9 +219,22 @@ def autoclass(clsname):
|
|||
|
||||
classDict[name] = JavaMultipleMethod(signatures)
|
||||
|
||||
def _getitem(self, index):
|
||||
try:
|
||||
return self.get(index)
|
||||
except JavaException as e:
|
||||
# initialize the subclass before getting the Class.forName
|
||||
# otherwise isInstance does not know of the subclass
|
||||
mock_exception_object = autoclass(e.classname)()
|
||||
if Class.forName("java.lang.IndexOutOfBoundsException").isInstance(mock_exception_object):
|
||||
# python for...in iteration checks for end of list by waiting for IndexError
|
||||
raise IndexError()
|
||||
else:
|
||||
raise
|
||||
|
||||
for iclass in c.getInterfaces():
|
||||
if iclass.getName() == 'java.util.List':
|
||||
classDict['__getitem__'] = lambda self, index: self.get(index)
|
||||
classDict['__getitem__'] = _getitem
|
||||
classDict['__len__'] = lambda self: self.size()
|
||||
break
|
||||
|
||||
|
|
|
@ -14,3 +14,10 @@ class ReflectTest(unittest.TestCase):
|
|||
stack.push('world')
|
||||
self.assertEqual(stack.pop(), 'world')
|
||||
self.assertEqual(stack.pop(), 'hello')
|
||||
|
||||
def test_list_iteration(self):
|
||||
ArrayList = autoclass('java.util.ArrayList')
|
||||
words = ArrayList()
|
||||
words.add('hello')
|
||||
words.add('world')
|
||||
self.assertEqual(['hello', 'world'], [word for word in words])
|
||||
|
|
Loading…
Reference in New Issue