The java::listify command trasforms a java collection or a java enumeration in a tcl-list.
The collectionORenumertion object is a handle to a Java object that implements the java.util.Collection
interface or the java.util.Enumeration
interface, or an handle to null
The java::listify command is similar to the getrange method working on a java-array, except that elements can be of different classes.
In its simpler form (without -noconvert> or class),java::listify
tries to convert the enum/collections's elements in simple tcl-types (i.e. strings !).
This implicit conversions works only on basic elements (i.e. Integer, Double, .., String);
otherwise the element is extracted as a java-object.
Note that null elements are converted to the empty string.
If -noconvert option is used, then all collection's elements are returned
as java.objects.
If class is specified, then all collection's elements are returned
as casted java.objects. An error is raised if class is incompatible with any element.
Assume for a moment that the user has defined a Java class.
This class contains a static method that returns a
collection object. The JDK 1.5 code to iterate over this
collection would be:
This same iteration could be implemented in Tcl, using
the java::listify command.
Collection<String> c = MyJavaClass.getCollection();
for (String elem : c) {
System.out.println("elem is " + elem);
}
set c [java::call MyJavaClass getCollection]
foreach elem [java::listify {String} $c] {
puts "elem is $elem"
}
The java::listify command can be used to iterate
over elements in a Hashtable or any other Map implementation.
The code above will print the following to the console:
java::import -package java.util Hashtable Map
set t [java::new Hashtable]
$t put "One" "onestr"
$t put "Two" "twostr"
foreach e [java::listify {java.util.Map.Entry} [$t entrySet]] {
set key [[$e getKey] toString]
set value [[$e getValue] toString]
puts "$key -> $value"
}
One -> onestr
Two -> twostr
The java::listify command supports automatic conversion
of a Java primitive wrapper in a collection to a Tcl
value. For example, given a Vector of java.lang.Integer
,
its elements are automatically converted in Tcl-integers.
set v [java::new java.util.Vector]
$v addElement [java::new Integer 0]
$v addElement [java::new Integer 1]
$v addElement [java::new Integer 2]
puts "vector elements are: [java::listify $v]"
Based on TclBlend Copyright © 1997-1998 Sun Microsystems, Inc.
JBlend is Copyright © 2016 - Irrational Numbers.