The block should take the same
arguments as the method or methods in question, and a last argument that is a string that
names the method called. If the interface methods take different lengths of arguments, you
can use *args instead. For an explicit example, you could create an implementation of
KeyListener like this:
java.awt.event.KeyListener.impl do |method, e|
case method
when "keyPressed": puts "A key was pressed"
when "keyReleased": puts "A key was released"
when "keyTyped": puts "A key was typed"
end
end
Of course, in many cases you don??™t care what method was called, and in those cases you
can just name the method argument to an underscore or something else. If you don??™t need any
arguments to the method, such as Runnable, you can just omit the arguments:
java.lang.Runnable.impl do
puts "Running"
end
Note that the impl method creates a new anonymous class beneath the covers that calls
the block. There??™s nothing strange going on; the Java integration layer just hides those parts.
At the moment, most of the Java integration layer is totally written in pure Ruby, and the parts
involved in the impl method don??™t use any Java at all.
You can use the initialize method in the same way as you do from Ruby. In earlier versions
of JRuby this didn??™t work as expected, and you had to call super explicitly to avoid
strange errors. This is no longer true; both initialize and super calls in initialize work as
you would like them to:
class Abc
import java.
Pages:
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193