21 Nov 2013

Java Reflection

1.How to know the method which is calling this method?


Reflection.getCallerClass(realFramesToSkip) //here realFramesToSkip is how many level you want to go up, for immediate caller you should use 1, if you want a method 1 level up then 2 etc.


2. How to get the parameters of a method in class?


public class Employee{

   private String strFirstName, strLastName;
   
   public void setStrFirstName(String strFirstName){
               this.strFirstName = strFirstName;
   }

    public String getStrFirstName(){
               return strFirstName;
   }
}

public class Demo{
    public static void main(String[] args){
         Class classEmp = Employee.class;
         Method methodSetstrFirstName =                                                           classEmp.getMethod("setStrFirstName");
         Parameter[]  params = method.getParameters();
        for(int m=0; m<params.length;m++)
 {
Parameter param = params[m];
String paramName = param.getName();
String paramType = param.getType().getSimpleName();
            System.out.println("Name:"+paramName+" Type:"+paramType);
         }

}

Output:

Name:setStrFirstName Type:String

Note: getParameters method on class Method is available only from java8, refer the docs here.