一般在综合系统中,我们都会写一个菜单,然后switch匹配调用,对不对?
但是如果我有一万个方法供选择呢?
我要去写一万遍case+方法+ break吗??
这里就体现出反射的牛逼之处了。
Method[] declaredMethods = this.getClass().getDeclaredMethods();
//获取当前类所有的方法
for (Method method : declaredMethods) {
//增强for循环遍历
String name = method.getName();
//获取方法名字
if (key.equals(name)) {
//根据输入来匹配方法名字
method.invoke(this);
//反射调用方法
}
}
不管有多少个哪怕十万个方法,我都只需要写这么点代码。