Day16_88_通过反射机制执行方法

通过反射机制执行方法

 * method.invoke(object,"admin","123");  

* 代码

  import java.lang.reflect.InvocationTargetException;
  import java.lang.reflect.Method;

  public class ReflectTest16 {
      public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
          //获取类
          Class c= Class.forName("com.shige.Reflect.CustomerService");

          //获取某个特定的方法
          Method method=c.getDeclaredMethod("login", String.class, String.class); //方法名  参数类型.class  参数类型.class

          //通过反射机制执行login方法
          Object object=c.newInstance();

          //调用object对象的,method方法,传入"admin","123"参数,返回值是一个Object
          Object resValue=method.invoke(object,"admin","123");

          //输出
          System.out.println(resValue);  //true
      }
  }
posted @ 2021-04-11 11:58  失昼  阅读(43)  评论(0)    收藏  举报