一段动态获得和执行方法的代码

来源:互联网 发布:C语言node 编辑:程序博客网 时间:2024/05/17 00:10


/**
  * Override to run the test and assert its state.
  * @exception Throwable if any exception is thrown
  */
 protected void runTest() throws Throwable {
  assertNotNull(fName);
  Method runMethod= null;
  try {
   // use getMethod to get all public inherited
   // methods. getDeclaredMethods returns all
   // methods of this class but excludes the
   // inherited ones.
   runMethod= getClass().getMethod(fName, null);
  } catch (NoSuchMethodException e) {
   fail("Method /""+fName+"/" not found");
  }
  if (!Modifier.isPublic(runMethod.getModifiers())) {
   fail("Method /""+fName+"/" should be public");
  }

  try {
   runMethod.invoke(this, new Class[0]);
  }
  catch (InvocationTargetException e) {
   e.fillInStackTrace();
   throw e.getTargetException();
  }
  catch (IllegalAccessException e) {
   e.fillInStackTrace();
   throw e;
  }
 }


在看到这段代码之前,根本就没有想到Class会有getMethod这个方法,更没有想到会这么用,而且用得如此之妙。
原创粉丝点击