Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program to find the number of methods in a java program

Tags:

java

I used the following code to identify the number of functions in a class. Similar way can any one help me to identify the number of functions in a java program. In my program i gave input file as a class. Guide me with the code to give input as a java program and to find the number of declared functions in it.

import java.lang.reflect.*;
import java.io.*;
import java.lang.String.*;
   public class Method1 {
      private int f1(
       Object p, int x) throws NullPointerException
      {
         if (p == null)
            throw new NullPointerException();
         return x;
      }

      public static void main(String args[])throws Exception
      {
         int Mcount=0,MthdLen=0;
         try {
           Class cls = Class.forName("Madhu");
        int a;
            Method methlist[]= cls.getDeclaredMethods();
            for (int i = 0; i < methlist.length;i++)
            {  
               Method m = methlist[i];
               Mcount = Mcount + 1;
               MthdLen=MthdLen+(m.getName().length());
            }
         }
         catch (Throwable e) {
            System.err.println(e);
         }
        System.out.println("Length = " + MthdLen);
        System.out.println("Mcount = " + Mcount);
      }
   }
like image 912
Madhushudhanan Avatar asked Dec 17 '22 15:12

Madhushudhanan


1 Answers

First of all,

 Class cls = Class.forName("Madhu");

Requires the fully qualified name of the desired class. e.g Class.forName("java.lang.Thread")'.

Secondly,

 Method methlist[]= cls.getDeclaredMethods();

returns public, protected, private and default method of that specific class only (it excludes inherited methods).

Thirdly,

MthdLen=MthdLen+(m.getName().length());

Sums up the string length of the method name. What do you need this for? You could simply do a count as follows:

int MCount = cls.getDeclaredMethods().length; //If the "getDeclaredMethods()` doesn't return a null.

Finally, if you need to get all inherited public & protected methods of that class, you would do

Class<?> class2 = cls.getSuperClass();

//Get all methods using
Method[] methods2 = class2.getDeclaredMethods();

//Iterate through methods2 and retrieve all public, protected methods and add it to MCount.

Hope this helps.

like image 50
Buhake Sindi Avatar answered Dec 29 '22 06:12

Buhake Sindi