Monday, April 30, 2012

How can I count the number of methods in a Java class ?

Here it is a simple solution for the same. You can print the count and method headers with this code.

import java.lang.reflect.Method;
/**
 *
 * @author K.A.N. Nancy
 */
public class CountClassMethods {
    public static void main(String args[]){
        Class className=null;
       try{
          className= Class.forName(args[0]);
          Method[] methods= className.getMethods();
           System.out.println("Number of methods in "+className+" = "+methods.length);
           for(int i=0;i<methods.length;i++){
               System.out.println(methods[i]);
           }
       }catch(ClassNotFoundException classNotFoundException){
           System.out.println("Class "+className+" could not be found");
       }

    }

Coded @ Feb 29, 2012 -  4:10 am IST

2 comments:

  1. Nancy, thanks for the wonderful post. It is always interesting to study reflection. It was indeed one of my favorite topics.
    .
    So, here is a tip to add on:
    .
    The above program outputs all PUBLIC methods of the class XXX along with the public methods of the super class (perhaps ‘Object’, if it does not have a super class).
    .
    To restrict the program to print all the methods of current class (say XXX) including all the public, private, static, protected and default methods and excluding all the methods of the super class:
    .
    Use className.getDeclaredMethods();

    ReplyDelete