Shorthand bean constructor?

Let’s say I have a Book class in Java that has an author and title
fields.
I think in Groovy I could write something like:

def book = new Book(title: “Foo”, author: “Bar”)

and Groovy would automatically construct the bean and call the setters
for
those fields. It’s just a shorthand way of constructing Java beans I
think.
Is there anything like this with the Java integration that JRuby has?
I
was hoping for something like:

book = Book.new({:title => “Foo”, :author => “Bar”)

but that doesn’t work. Anyone know of something like this?

Joe

There’s nothing built-in, but you can easily write your own.

module BeanLikeConstructor
def new(attrs = {})
super().tap |obj|
attrs.each do |k,v|
obj.send("#{k}=", v) if obj.respond_to?("#{k}=")
end
end
end
end

class Book
extend BeanLikeConstructor
end

book = Book.new(:title => “Foo”, :author => “Bar”)

/Nick

On Thu, Mar 31, 2011 at 11:05 AM, Nick S. [email protected]
wrote:

end

class Book
extend BeanLikeConstructor
end

book = Book.new(:title => “Foo”, :author => “Bar”)

I’m pretty sure many other ways would be there. I think of below:

proc = lambda {|k,v| b = Book.new; b.set_title(k); b.set_author(v); b}
book = proc.call(‘Foo’, ‘Bar’)

-Yoko

How cool, Nick.
Don’t mean to derail the thread, but I didn’t know about “tap”. Very
sweet
method!

Cheers,
–Bob

Thanks, that’s what I figured. I’m giving a little presentation on
JRuby
and I wanted to show all the handy features you can utilize. Would
there be
any desire to add this to the Java integration? Seems like a handy
thing to
have.

Joe

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs