Instantiating a object from a string
8:01 PM EDT Tuesday, August 28 2007
Today, while doing some Ruby programming, I needed to create an instance of a class (instantiate an object), but I didn't have the class name, just the class name in a string. Here's a Ruby method that takes the name of the class as a string and returns an instance of that class:
def create(class_name)
Object.const_get(class_name).new
end
So if you do this:
create "Array"
You get an instance of an Array, in other words, the equivalent of Array.new. And in Rails, you can do:
def create(class_name)
class_name.constantize.new
end
That's cool. It got me thinking, how do you do this in other languages? Here's what I came up with:
//JavaScript
function create(class_name) {
return eval("new "+class_name+"()")
}
Got any others? Perl? Python? Lisp? Erlang? PHP? C? Java?