[英]One parameter (@RequestParam String tab) - many methods
I get "tab" from front, his value can be 'profile', 'active', 'summary', 'votes' etc. Each value has its own method.我从前面得到“tab”,他的值可以是“profile”、“active”、“summary”、“votes”等。每个值都有自己的方法。 How can I call a method based on the value of 'tab' without using switch and if .如何在不使用switch和if的情况下根据 'tab' 的值调用方法。 Are there any patterns for this case?这种情况有什么模式吗?
I think the Decorator Pattern is a good solution for that, see the solution bellow:我认为装饰器模式是一个很好的解决方案,请参见下面的解决方案:
Tab
:创建一个到Tab
的接口:public interface Tab {
String methodName();
}
Implement the classes for this interface: ActiveTab
, ProfileTab
, SummaryTab
实现此接口的类: ActiveTab
、 ProfileTab
、 SummaryTab
Create an Enum to understand and convert the parameter:创建一个 Enum 来理解和转换参数:
public enum TabTypeEnum {
PROFILE(ProfileTab.class), ACTIVE(ActiveTab.class), SUMMARY(SummaryTab.class);
Class<? extends Tab> tabClazz;
TabTypeEnum(Class<? extends Tab> tabClazz) {
this.tabClazz = tabClazz;
}
public static Tab getTabClazz(String tab) throws IllegalAccessException, InstantiationException {
return TabTypeEnum.valueOf(tab.toUpperCase()).tabClazz.newInstance();
}
}
public class TabDecorator implements Tab {
protected Tab tab;
public TabDecorator(String tab) {
try {
this.tab = TabTypeEnum.getTabClazz(tab);
} catch (NullPointerException | IllegalArgumentException | IllegalAccessException | InstantiationException e) {
throw new InvalidTabException(tab);
}
}
@Override
public String methodName() {
return this.tab.methodName();
}
}
@GetMapping("/")
public String getByTabParam(@RequestParam String tab) {
return new TabDecorator(tab).methodName();
}
Se the solution working: https://github.com/armandoalmeida/tab-problem-stackoverflow解决方案工作: https://github.com/armandoalmeida/tab-problem-stackoverflow
With reflection?用反射?
MyClass c = new MyClass();
Method m = c.getClass().getMethod(value);
m.invoke(c);
Where MyClass contains methods with name correspond to the values.其中 MyClass 包含名称对应于值的方法。
Although I think this is discouraged because Java compiler wouldn't be able to detect errors.虽然我认为这是不鼓励的,因为 Java 编译器无法检测到错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.