我已经在下面的代码中进行了开发,旨在消除其他情况,以便使代码的循环复杂度降低。为此,我使用了反射api并编写了将条件作为参数的方法,并在条件名称的基础上调用了相应的方法。这很好用,我想知道在Web应用程序中使用反射(此代码)是个好主意,这样我就不必检查条件了。
例如,在下面的代码中,我们有不同的方法,其前缀状态为ex:stateSUBMIT,stateWithdraw等。我们可以通过仅传递“ SUBMIT”来调用stateSUBMIT方法。
public class Participate {
public String execute(String methodName) {
String st = null;
try {
Method method = this.getClass().getDeclaredMethod(
"state" + methodName);
method.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
return st;
}
public void stateSUBMIT() {
System.out.println("in SUBMIT");
}
public void stateWithdraw() {
System.out.println("in Withdraw");
}
public void state() {
System.out.println("in state ");
}
public void statenull() {
System.out.println("in null ");
}
public static void main(String[] args) {
Participate p = new Participate();
p.execute("SUBMIT");
}
}
这是有效的代码,但无需任何反射即可实现。
第一步:定义一个接口
public interface Command {
public void execute();
}
第二步:创建具体实现
public class StateCommand implements Command {
public void execute() {
// Your code.
}
}
第三步:将这些集合添加到您的原始课程中
private Map<String, Command> commands;
第四步:填充
public MyClass() {
commands = new HashMap<String, Command>();
commands.put("state", new StateCommand());
}
获取该类并执行
public String callMethod(String name) {
Command command = commands.get(name);
if(command != null) {
command.execute();
}
}
这只是使用反射的一种相对简单的替代方法,应将其视为万不得已的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句