Skip to content

Commit

Permalink
Convert Java iterators to Julia iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
aviks committed Dec 6, 2016
1 parent 3ff3411 commit e4c4902
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/convert.jl
Expand Up @@ -174,7 +174,7 @@ function unsafe_string(jstr::JString) #jstr must be a jstring obtained via a JN
end

#This is necessary to properly deprecate bytestring in 0.5, while ensuring
# callers don't need to change for 0.4.
# callers don't need to change for 0.4.
function Base.bytestring(jstr::JString) #jstr must be a jstring obtained via a JNI call
if VERSION >= v"0.5.0-dev+4612"
Base.depwarn("bytestring(jstr::JString) is deprecated. Use unsafe_string(jstr) instead", :bytestring )
Expand Down Expand Up @@ -218,3 +218,13 @@ function convert{T}(::Type{Array{T, 1}}, obj::JObject)
end
return ret
end

##Iterator
Base.start(itr::JavaObject) = true
function Base.next(itr::JavaObject, state)
o = jcall(itr, "next", @jimport(java.lang.Object), (),)
c=jcall(o,"getClass", @jimport(java.lang.Class), ())
t=jcall(c, "getName", JString, ())
return (convert(JavaObject{Symbol(t)}, o), state)
end
Base.done(itr::JavaObject, state) = (jcall(itr, "hasNext", jboolean, ()) == JNI_FALSE)
36 changes: 36 additions & 0 deletions test/runtests.jl
Expand Up @@ -148,6 +148,42 @@ jobj = jcall(T, "testArrayAsObject", JObject, ())
arr = convert(Array{Array{UInt8, 1}, 1}, jobj)
@test ["Hello", "World"] == map(Compat.String, arr)

#Test iterator conversions

JArrayList = @jimport(java.util.ArrayList)
a=JArrayList(())
jcall(a, "add", jboolean, (JObject,), "abc")
jcall(a, "add", jboolean, (JObject,), "cde")
jcall(a, "add", jboolean, (JObject,), "efg")

t=Array{Any, 1}()
for i in jcall(a, "iterator", @jimport(java.util.Iterator), ())
push!(t, unsafe_string(i))
end

@test length(t) == 3
@test t[1] == "abc"
@test t[2] == "cde"
@test t[3] == "efg"

#Different iterator type - ListIterator
t=Array{Any, 1}()
for i in jcall(a, "listIterator", @jimport(java.util.ListIterator), ())
push!(t, unsafe_string(i))
end

@test length(t) == 3
@test t[1] == "abc"
@test t[2] == "cde"
@test t[3] == "efg"

#Empty List
a=JArrayList(())
t=Array{Any, 1}()
for i in jcall(a, "iterator", @jimport(java.util.Iterator), ())
push!(t, unsafe_string(i))
end
@test length(t) == 0

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

0 comments on commit e4c4902

Please sign in to comment.