Skip to content

Commit

Permalink
Merge pull request #271 from InvalidCo/list_getitem_indexerror
Browse files Browse the repository at this point in the history
for...in iteration of list interfaces
  • Loading branch information
tito committed Aug 22, 2017
2 parents 6f8d846 + b4d2d50 commit efe610b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
18 changes: 16 additions & 2 deletions jnius/reflect.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

from .jnius import (
JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod,
JavaField, JavaStaticField, JavaMultipleMethod, find_javaclass
JavaField, JavaStaticField, JavaMultipleMethod, find_javaclass,
JavaException
)


Expand Down Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions tests/test_reflect.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,10 @@ def test_stack(self):
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])

0 comments on commit efe610b

Please sign in to comment.