public
Created

Illustrates problem instantiating Ruby subclass of Java class w/different constructor arities.

  • Download Gist
jruby-2457.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
require 'java'
 
java_import 'java.lang.Runnable'
 
class SampleRunnable
include Runnable
 
def initialize(greeting)
@greeting = greeting
end
def run
puts @greeting
end
end
 
# new_thread = java.lang.Thread.new(SampleRunnable.new)
# new_thread.start
# new_thread.join
 
# Yields:
# >ruby jruby-2457.rb
# ArgumentError: wrong number of arguments (0 for 1)
# (root) at jruby-2457.rb:19
 
 
# Workaround:
 
class WorkaroundRunnable
attr_accessor :greeting
include Runnable
 
def self.create_instance(greeting)
instance = WorkaroundRunnable.new
instance.greeting = greeting
instance
end
def run
puts @greeting
end
end
 
new_thread = java.lang.Thread.new(WorkaroundRunnable.create_instance("I'm a workaround."))
new_thread.start
new_thread.join
 
# Yields:
 
# >ruby jruby-2457.rb
# I'm a workaround.
 
# The workaround is usually fine. However, there may be cases where Ruby code is
# instantiating different classes, and assuming that it can call new with the
# parameter (in this case, the greeting param).

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.