主要通过Java反射机制实现。
例如:
public class NewClass { private static final NewClass newClass = new NewClass(); public void doTest(String methodName){ try { newClass.getClass().getMethod(methodName, new Class[]{}).invoke(newClass, new Object[]{}); } catch (Exception ex) { Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex); } } public void speak(){ System.out.println("speak"); } public void running(){ System.out.println("running"); } }
public class Test { public static void main(String[] args) { NewClass newClass = new NewClass(); newClass.doTest("speak"); newClass.doTest("running"); } }
运行结果:
run: speak running 成功构建 (总时间: 0 秒)
时间: 2024-10-18 14:17:46