Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
May 18, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 < methods.length; i++) {
6.        StringBuffer methodBuf = new StringBuffer();

7.        methodBuf.append(methods[i].getReturnType().getName());
8.        methodBuf.append(" " + methods[i].getName());
9.        Class[] paramTypes = methods[i].getParameterTypes();
11.     System.out.println(paramTypes.length);
12.     methodBuf.append("(");
13.     if (paramTypes.length > 0)
14.       methodBuf.append(paramTypes[0] + " param_0");

15.     for (int j = 1; j < paramTypes.length; j++) {
16.       methodBuf.append(", " + paramTypes[j] + " param_" + j);
17.     }
18.     methodBuf.append(");");
19.     methodStrings[i] = methodBuf.toString();
20.   }
21.   return methodStrings;
22. } 
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 = \n");
4. for (int i = 0; i < methods.length; i++) {
5.   System.out.println(methods[i]);
Ajit Sagar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date