Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Created August 18, 2012 22:48
Show Gist options
  • Save keithrbennett/3390231 to your computer and use it in GitHub Desktop.
Save keithrbennett/3390231 to your computer and use it in GitHub Desktop.
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