Run as Java class and method string name

I got Java class or method name as a string and looked for it to be executed.

package classname;

public class AppTest{
    public void printIt(){
      System.out.println("printIt() no param");
    }
    
    public void printItString(String temp){
      System.out.println("printIt() with param String : " + temp);
    }
    
    public void printItInt(int temp){
      System.out.println("printIt() with param Int : " + temp);
    }



package classname;

import java.lang.reflect.Method;

public class ReflectApp{
  public static void main(String[] args){
    Class noparams[]={};
    
    Class[] paramString=new Class[1];
    paramString[0]=String.class;
    
    Class[] paramInt=new Class[1];
    paramInt[0]=Integer.TYPE;
    
    try{
      Class cls=Class.forName("classname.AppTest");
      Object obj=cls.newInstance();
      
      Method method=cls.getDeclaredMethod("printIt", noparams);
      method.invoke(obj,null);
      
      method=cls.getDeclaredMethod("printItString", paramString);
      method.invoke(obj, new String("AA"));
      
      method=cls.getDeclaredMethod("printItInt", paramInt);
      method.invoke(obj, 123);
    }catch(Exception e){
      e.printStackTrance();
    }
  }
}

If you run it, the result is


printIt() no param
printIt() with param String : AA
printIt() with param Int : 123

As you can see from the source above, you can see that the class name and method name were executed as strings.

댓글

이 블로그의 인기 게시물

Visual studio code Create shortcuts like Eclipse