2006-08-10

Java vs. Ruby: Reflection

Java:
public static Object create(Class c, String value) throws Exception {
  Constructor ctor = c.getConstructor( new Class[] { String.class } );
  return ctor.newInstance( new Object[] { value } );
}
public static void main (String args[]) throws Exception {
  Greeting g = (Greeting) create(Greeting.class, "Hello");
  g.show();
}


Ruby equivalent:
def create(klass, value)
  klass.new(value)
end
g = create(Greeting, "Hello")
g.show

Reference: 10 Things Every Java Programmer Should Know About Ruby