[rjb-users] Extending a Java class
rjb-users at rubyforge.org
rjb-users at rubyforge.org
Tue Oct 31 19:24:54 EST 2006
Hi Rich,
At this time, the imported class is not a really Ruby class in Rjb.
If you think it's better to map imported class as Ruby's class, I positively
plan to implement the feature.
So, at this time, a workaround is to use delegation instead of
inheritance.
This sample code describes how to delegate method calls to the contained
object.
require 'rjb'
require 'test/unit'
class RubyVector
Vector = Rjb::import('java.util.Vector')
def initialize
@vector = Vector.new
end
def test_vector
'it worked'
end
def method_missing(msg, *arg)
@vector.send(msg, *arg)
end
end
class VectorTest < Test::Unit::TestCase
def setup
@r = RubyVector.new
end
def test_adding_method()
assert_equal('it worked', @r.test_vector)
end
def test_add()
@r.add(1)
@r.add(2)
@r.add(3)
assert(@r.contains(1))
assert(!@r.contains(8))
end
def test_get()
@r.add("ab")
@r.add("cd")
@r.add("ef")
assert_equal("ab", @r.get(0).toString)
assert_equal("cd", @r.get(1).toString)
assert_equal("ef", @r.get(2).toString)
end
def test_iterator()
@r.add("ab")
@r.add("cd")
@r.add("ef")
i = @r.iterator
assert(i.hasNext)
assert_equal("ab", i.next.toString)
assert(i.hasNext)
assert_equal("cd", i.next.toString)
assert(i.hasNext)
assert_equal("ef", i.next.toString)
assert(!i.hasNext)
end
end
Best reagrds
On Mon, 30 Oct 2006 22:07:02 -0800 (PST)
richard apodaca <rich_apodaca at yahoo.com>さん wrote:
> Hi Arton,
>
> I was wondering how to extend a Java class with RJB. I
> saw in the documentation how to bind a Java interface
> to a Ruby class, but can I extend a Java class with
> Ruby? Here's an example of what I've tried:
>
> require 'rubygems'
> require_gem 'rjb'
> require 'rjb'
>
> Vector=Rjb::import 'java.util.Vector'
>
> class Test < Vector.class
> def initialize
> end
> def test_vector
> puts "it worked"
> end
> end
>
> t=Test.new # => TypeError: allocator undefined for
> Test
>
> I get a TypeError with the above code. If I try to
> extend directly form Vector rather than Vector.class,
> I get:
>
> TypeError: superclass must be a Class
>
> Any ideas?
>
> thanks,
> Rich
>
>
> ____________________________
> Richard Apodaca
> Blog: http://depth-first.com
>
>
>
> ____________________________________________________________________________________
> Want to start your own business? Learn how on Yahoo! Small Business
> (http://smallbusiness.yahoo.com)
>
--
arton
--------------------- Original Message Ends --------------------
--
arton
More information about the rjb-users
mailing list