diff --git a/jnius/reflect.py b/jnius/reflect.py index a85b832..e49cbd0 100644 --- a/jnius/reflect.py +++ b/jnius/reflect.py @@ -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 diff --git a/tests/test_reflect.py b/tests/test_reflect.py index fc6e8c9..778614d 100644 --- a/tests/test_reflect.py +++ b/tests/test_reflect.py @@ -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])