CSC/ECE 517 Summer 2008/wiki1 3 ref

From Expertiza_Wiki
Revision as of 02:36, 7 June 2008 by Hkdavis (talk | contribs)
Jump to navigation Jump to search

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.


Ruby v. Java 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 Java, the indexOf(String) method is used to find the index of a substring in a given String

       "Hello World".indexOf("W");

To use reflection to make this method call requires the following code:

       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();
       }

As you can see, this requires creating arrays of Class objects to specify parameter types, and possibly casting the result of the method call from Object to the correct type.

In Ruby, the same method call is:

       "Hello World".index("W")

Using reflection, this is reduced to a simple 3 lines of code

       s = "Hello World"
       method = s.method("index")
       method.call("W")


Java reflection tutorial

java.lang.reflect package api java.lang.Class api Reflection, ObjectSpace, and Distributed Ruby