反射用法

来源:互联网 发布:南昌淘宝摄影招聘 编辑:程序博客网 时间:2024/06/03 13:53

一。写个类

public class Simple {
 private void displayMessage(String strMsg) {
  System.out.println("message is:" + strMsg);
 }
}

二。反射调用

import java.lang.reflect.*;

public class Test {

 
 public static void main(String[] args) throws ClassNotFoundException,
   SecurityException, NoSuchMethodException, InstantiationException,
   IllegalAccessException, IllegalArgumentException,
   InvocationTargetException {

  Class simpleClass = Class.forName("Simple");
  Object simpelObject = simpleClass.newInstance();
  Class[] args1 = new Class[1];
  args1[0] = String.class;

  Method simpleMethod = simpleClass.getDeclaredMethod("displayMessage",
    args1);

  simpleMethod.setAccessible(true);

  String[] argments = new String[1];
  argments[0] = "Hello,world";
  simpleMethod.invoke(simpelObject, argments);

 }
}
原创粉丝点击