In this tutorial we are going to learn how to get method details of a class . In java, methods are classified into two types they are .
1) Instance methods
2) Static methods
Every method contains the following information
1) Return type
2) Method name
3) Method parameters
For better understanding , see the below example .
package com.java; import java.lang.reflect.Method; class Sample { protected int sum(int b, int c){ return b+c; } public String concat(String d,String e){ return e.concat(d); } public static void main(String[] args) throws Exception { Class c1=Class.forName("com.java.Sample"); Sample gcd=new Sample(); Method methods[]=c1.getDeclaredMethods(); for(Method m:methods) { System.out.println("method name is : "+m.getName()); System.out.println("return type is : "+m.getReturnType()); System.out.println("arguments types are : "); Class c2[]=m.getParameterTypes(); for(Class c3:c2) { System.out.println(c3.getName()); } } } } /* Output : method name is : main return type is : void arguments types are : [Ljava.lang.String; method name is : concat return type is : class java.lang.String arguments types are : java.lang.String java.lang.String method name is : sum return type is : int arguments types are : int int */
If we use getDeclaredMethods(), we will get particular class methods ( public , private , protected , default ) only and it’s super class methods are excluded. If we use getMethods(), we will get all public methods including super class public methods also. If we use getMethods() in the above example, along with public methods of class Sample, we will get public methods of java.lang.Object class also.