java 版本是这样的(为了清楚起见,我删除了导入和异常)。
public class FindAndRunStaticMethods {
public static void main(String[] args) {
fireAllRules();
}
public static void fireAllRules() {
for(Method method : StaticMethodClass.class.getDeclaredMethods()) {
findAndRunRules(method);
}
}
private static void findAndRunRules(Method method) {
if (!Modifier.isStatic(method.getModifiers())) return;
if (!method.getName().startsWith("rule")) return;
if (!method.getReturnType().equals(Void.TYPE)) return;
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1) return;
if (!parameterTypes[0].equals(File.class)) return;
method.invoke(null, new File("dummy"));
}
}
示例测试类可能如下所示
public class StaticMethodClass {
public static void ruleHere(File x) { System.out.println("should print"); }
public static void ruleRun(File x) { System.out.println("should print"); }
public void ruleNotSelected() { System.out.println("not run"); }
}