Last semester, my two main programming courses were CS 315 and CS 310 where we learned to use Lisp and LC-3 assembly code respectively. In both, programs and data were of the same format, so modifying a program was as simple as modifying data. In Java, however, it’s a bit more awkward. Sure, you can treat a .java file as text and modify it, but what if you only have the .class file? Or what if you just want an easier way? Fortunately, Java provides a solution called reflection.
In our Software Design course, our first assignment of the semester is to use reflection to create Java programs called adaptors. I’ve just started with the assignment by playing around with the Java reflection library and figuring out how to use these tools, but I thought I’d share a simple example which may be much quicker to understand than the article linked to above.
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) {
// select the class to look into
Class myclass = String.class;
// check how many methods the class declares
Method[] methods = myclass.getDeclaredMethods();
System.out.println( "Number of methods in "
+ myclass.getName() + " class: " + methods.length + "\n" );
// select a method from the class
int methodNum = 52;
Method mymethod = methods[methodNum];
System.out.println( "Checking method #" + methodNum + ":" );
// name of method
System.out.println( "Name: " + mymethod.getName() );
// modifiers such as protected or static
// note: getModifiers() returns an int that you need the Modifier
// class to makes sense of
System.out.println( "Modifiers: "
+ Modifier.toString(mymethod.getModifiers()) );
// return type of method
System.out.println( "Return Type: " + mymethod.getReturnType().getName() );
// list of method's parameters
Class>[] mytypes = mymethod.getParameterTypes();
for (Class c: mytypes)
System.out.println( "Parameter: " + c.getName() );
}
}
The output for this program is:
Number of methods in java.lang.String class: 68
Checking method #52:
Name: substring
Modifiers: public
Return Type: java.lang.String
Parameter: int
Parameter: int