Skip to content

Commit e4c4902

Browse files
committed
Convert Java iterators to Julia iterators
1 parent 3ff3411 commit e4c4902

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/convert.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ function unsafe_string(jstr::JString) #jstr must be a jstring obtained via a JN
174174
end
175175

176176
#This is necessary to properly deprecate bytestring in 0.5, while ensuring
177-
# callers don't need to change for 0.4.
177+
# callers don't need to change for 0.4.
178178
function Base.bytestring(jstr::JString) #jstr must be a jstring obtained via a JNI call
179179
if VERSION >= v"0.5.0-dev+4612"
180180
Base.depwarn("bytestring(jstr::JString) is deprecated. Use unsafe_string(jstr) instead", :bytestring )
@@ -218,3 +218,13 @@ function convert{T}(::Type{Array{T, 1}}, obj::JObject)
218218
end
219219
return ret
220220
end
221+
222+
##Iterator
223+
Base.start(itr::JavaObject) = true
224+
function Base.next(itr::JavaObject, state)
225+
o = jcall(itr, "next", @jimport(java.lang.Object), (),)
226+
c=jcall(o,"getClass", @jimport(java.lang.Class), ())
227+
t=jcall(c, "getName", JString, ())
228+
return (convert(JavaObject{Symbol(t)}, o), state)
229+
end
230+
Base.done(itr::JavaObject, state) = (jcall(itr, "hasNext", jboolean, ()) == JNI_FALSE)

test/runtests.jl

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,42 @@ jobj = jcall(T, "testArrayAsObject", JObject, ())
148148
arr = convert(Array{Array{UInt8, 1}, 1}, jobj)
149149
@test ["Hello", "World"] == map(Compat.String, arr)
150150

151+
#Test iterator conversions
152+
153+
JArrayList = @jimport(java.util.ArrayList)
154+
a=JArrayList(())
155+
jcall(a, "add", jboolean, (JObject,), "abc")
156+
jcall(a, "add", jboolean, (JObject,), "cde")
157+
jcall(a, "add", jboolean, (JObject,), "efg")
158+
159+
t=Array{Any, 1}()
160+
for i in jcall(a, "iterator", @jimport(java.util.Iterator), ())
161+
push!(t, unsafe_string(i))
162+
end
163+
164+
@test length(t) == 3
165+
@test t[1] == "abc"
166+
@test t[2] == "cde"
167+
@test t[3] == "efg"
168+
169+
#Different iterator type - ListIterator
170+
t=Array{Any, 1}()
171+
for i in jcall(a, "listIterator", @jimport(java.util.ListIterator), ())
172+
push!(t, unsafe_string(i))
173+
end
174+
175+
@test length(t) == 3
176+
@test t[1] == "abc"
177+
@test t[2] == "cde"
178+
@test t[3] == "efg"
179+
180+
#Empty List
181+
a=JArrayList(())
182+
t=Array{Any, 1}()
183+
for i in jcall(a, "iterator", @jimport(java.util.Iterator), ())
184+
push!(t, unsafe_string(i))
185+
end
186+
@test length(t) == 0
151187

152188
# At the end, unload the JVM before exiting
153189
JavaCall.destroy()

0 commit comments

Comments
 (0)