You can find the Java String there, but also all
other packages that can exist:
JString = Java::java.lang.String
HelloWorld = Java::se.ologix.HelloWorld
CHAPTER 6 ?– JAVA INTEGRATION 101
This can often make it much more obvious what??™s happening, even if it??™s slightly more
verbose.
So, when you have a class reference, what can you do with it? Well, you can do most of the
things with it from Java code. JRuby also tries to be smart about things, doing implicit conversions
of different kinds. Say that you want to call System.out.println from Ruby. You do it
mostly the same way:
java.lang.System.out.println("Hello, world")
It??™s important to notice that the "Hello, world" string is a Ruby String, not a Java String.
These are different types, but a Ruby String is converted beneath the covers for all obvious
cases. For example, a Ruby Fixnum matches against all the integer types in Java, and also the
primitive wrapper types. The goal with all this integration is that you won??™t have to care what
type objects are. For almost all cases, things will just work.
To create a new instance of a Java class, just call the new method on it:
m = java.util.HashMap.new
m.put "hello", "world"
m.put "goodbye", "life"
puts m.get("hello")
iter = m.keySet.iterator
while iter.hasNext
key = iter.next
puts "#{key}=#{m.get(key)}"
end
As you can see, all these things work more or less exactly as they would in Java. The big
difference is that you don??™t have to write parentheses in most cases, and you don??™t have to care
about the types of variables.
Pages:
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186