Create a gist now

Instantly share code, notes, and snippets.

Illustrates problem instantiating Ruby subclass of Java class w/different constructor arities.
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment