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?

Posted in  | Tags Rails, Javascript, Ruby

Comments Feed

1. In my experience you can almost always avoid eval() in javascript so here are my 2 cents:

function create(className) {
return new this[className];
}

There are, of course, other ways of doing that depending on what you need...

# Posted By Arni Hermann Reynisson on Tuesday, September 04 2007 at 06:15 EDT

Add a Comment