Determine an Object’s Behavior Using the Method Class

Determine an Object’s Behavior Using the Method Class

An object’s behavior is defined by the operations that can be performed on it. This in turn translates to the methods defined in the object’s type or class. Java’s reflection mechanism allows a program to determine the methods defined for an object at run time. This example discovers and returns all the methods defined for a Java object:

 1.    public String[] listMethods (Object o) {2.      Class c = o.getClass();3.      Method[] methods = c.getMethods();4.      String[]  methodStrings = new String[methods.length];5.      for (int i = 0; i  0)14.       methodBuf.append(paramTypes[0] + " param_0");15.     for (int j = 1; j 

The listMethods() method takes as input the object whose methods are to be listed. On Line 2, it obtains the object's class and then on Line 3, it obtains the array of methods. Lines 5-17 comprise a for{} loop in which the program goes through the array of methods and gets string equivalents of the characteristics of each method. Finally, on Line 19, the result, which is the method declaration, is stored in a String array that is returned to the calling method. Here is an example of invoking this method for an object "o":

 1. String[] methods = TestMethodReflection.getMethods(o);2. System.out.println("List of methods in a String object = 
");3. 	4. for (int i = 0; i 


Share the Post: