Reflection invoke method
file:DemoClass.java
public class DemoClass { private String strMsg; public void setMsg(String msg) { this.strMsg = msg; } public String getMsg() { return strMsg; } @Override public String toString() { return strMsg; } }
file:UseInvoke.java
public class UseInvoke { public static void main(String[] args) throws Exception { DemoClass demoClass = DemoClass.class.newInstance(); Method method = DemoClass.class.getMethod("setMsg"), String.class); // setting up message text. method.invoke(demoClass, "demomsg"); method = DemoClass.class.getMethod("getMsg"); System.out.println( "getMsg(): " + method.invoke(demoClass) ); System.out.println( "DemoClass.class.toString(): " + demoClass) ); } }
Result of java UseInvoke
実行結果
$ java UseInvoke getMsg(): demomsg DemoClass.class.toString(): demomsg