如何在具有相同类型参数的Java中创建方法? [英] How Can I Create method In Java With Same Type Parameter?
本文介绍了如何在具有相同类型参数的Java中创建方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下:
enum EnumType {
CATEGORY,
GROUP,
MAIN
}
方法:
public void call(EnumType type){
switch(type):
case CATEGORY:
return methodForCategory();
case GROUP:
return methodForGroup();
...
}
public void methodForCategory(){
... Operations according to EnumType.CATEGORY
}
public void methodForGroup(){
... Operations according to EnumType.GROUP
}
public void methodForMain(){
... Operations according to EnumType.MAIN
}
但是我想在不使用开关/大小写的情况下调用它;
But I want to call it without switch/case like below;
public void call(EnumType type){
methodForType(EnumType type);
}
有可能还是有更好的选择?
Is it possible or is there any better alternative?
推荐答案
您可以在枚举内创建方法实现,如下所示:
You can create the method implementation inside the enum as below:
public enum EnumType {
CATEGORY {
@Override
public void processMethod() {
// Do something here
}
},
GROUP {
@Override
public void processMethod() {
// Do something here
}
},
MAIN {
@Override
public void processMethod() {
// Do something here
}
};
public abstract void processMethod();
}
并将调用方法的实现更新为:
And update call method implementation as:
public void call(EnumType type){
type.processMethod();
}
由于方法返回类型为<$ c $,切换代码不应返回任何内容c> void 。
这篇关于如何在具有相同类型参数的Java中创建方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文