您的位置:首页 > 编程语言

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

2004-10-12 05:37 375 查看
/**
* 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这个方法,更没有想到会这么用,而且用得如此之妙。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: