CSC/ECE 517 Summer 2008/wiki1 3 ref
Reflection is built into Ruby, but in Java, it's a special API. Does this make Ruby code easier to write than Java code? Give examples of reflection sequences in both languages, and analyze which is clearer, and also, if possible, which is more efficient.
Java Reflection - The Java package for reflection is java.lang.reflect. Another important class for reflection is java.lang.Class. Java's reflection has limitations that Ruby's doesn't. An example of something Ruby can do is to iterate over all of the objects of a certain type. The ObjectSpace class in Ruby has a method each_object(), which iterates over each object that matches the type of it's parameter.
a = 102.7 b = 95.1 ObjectSpace.each_object(Numeric) {|x| p x }
This prints out the value of each Numeric type object that exists in the Ruby environment. Java's reflection api doesn't provide a mechanism to iterate over Objects that you don't already have a reference to.
Example -
In java, to print the names of all the methods an Object[] has, the following code is needed:
Object[] objArray = new Object[]{"Hello World"}; Method[] methods = objArray.getClass().getMethods(); for (Method m : methods) { System.out.println(m.getName()); }
In Ruby, the same functionality is a single line:
puts Array.methods
In this example, I use reflection to make this method call:
"Hello World".indexOf("W");
which returns 6.
String s = "Hello World"; Method method; try { method = s.getClass().getMethod("indexOf", new Class[]{String.class}); Object result = method.invoke(s, "W"); System.out.println(result); } catch(NoSuchMethodException nsme) { nsme.printStackTrace(); } catch(IllegalAccessException iae) { iae.printStackTrace(); } catch(InvocationTargetException ite) { ite.printStackTrace(); }
http://java.sun.com/docs/books/tutorial/reflect/index.html
http://java.sun.com/javase/6/docs/api/java/lang/reflect/package-summary.html http://java.sun.com/javase/6/docs/api/java/lang/Class.html http://phrogz.net/programmingruby/ospace.html