鉴于我有一个“空”界面:
public interface Color {
}
还有一个实现上述接口的枚举类:
public enum Fruits implements Color {
APPLE,
APRICOT,
AVOCADO,
BANANA,
BLACKBERRY,
BLUEBERRY,
CHERRY,
COCONUT,
CRANBERRY,
DATE,
DURIAN,
ELDERBERRY,
FIG,
JACKFRUIT,
KIWI,
LEMON,
LIME,
LYCHEE,
MANGO,
MELLON,
ORANGE,
PAPAYA,
PASSION_FRUIT,
PEAR,
PLUM,
PINEAPPLE,
POMELO
}
经过一段时间的编码,我回到那个界面并添加一个方法,例如:
public interface Color {
Color getColor();
}
IntelliJ Idea肯定会告诉我,每个枚举值都应实现新添加的方法。我现在能做的就是跳到每个枚举值(使用F2作为跳到每个值的快捷方式),然后转到ALT + ENTER创建它的默认实现。
APPLE {
@Override
public Color getColor() {
return null;
}
},
APRICOT {
@Override
public Color getColor() {
return null;
}
},
AVOCADO {
@Override
public Color getColor() {
return null;
}
},
...
一旦我意识到实现此接口的不仅仅是这个枚举,这将很快失去控制。
说明
我正在 IntelliJ Idea 中搜索 键盘快捷键 ,该IDE提供了生成代码的功能一次创建每个枚举值的空方法树桩。
IntelliJ Idea 确实为每个枚举值分别提供了这种功能,这引出了我的问题:可以一次为所有值完成此操作吗?
答案 0 :(得分:1)
可以。只需在界面上创建一个default method:
default String getSomething(Any any) {
return null;
}
答案 1 :(得分:0)
您可以在枚举类本身中提供默认的实现,而不是在每个枚举值中提供:
public enum DirectCallRate implements KeyPerformanceIndicator {
COUNT,
COUNT_ANSWERED,
COUNT_UNANSWERED,
COUNT_EXTERNAL,
COUNT_ANSWERED_EXTERNAL,
COUNT_UNANSWERED_EXTERNAL,
COUNT_INTERNAL,
COUNT_ANSWERED_INTERNAL,
COUNT_UNANSWERED_INTERNAL,
COUNT_INBOUND,
COUNT_ANSWERED_INBOUND,
COUNT_UNANSWERED_INBOUND,
COUNT_OUTBOUND,
COUNT_ANSWERED_OUTBOUND,
COUNT_UNANSWERED_OUTBOUND,
COUNT_EXTERNAL_OUTBOUND,
COUNT_ANSWERED_EXTERNAL_OUTBOUND,
COUNT_UNANSWERED_EXTERNAL_OUTBOUND,
COUNT_EXTERNAL_INBOUND,
COUNT_ANSWERED_EXTERNAL_INBOUND,
COUNT_UNANSWERED_EXTERNAL_INBOUND,
COUNT_INTERNAL_OUTBOUND,
COUNT_ANSWERED_INTERNAL_OUTBOUND,
COUNT_UNANSWERED_INTERNAL_OUTBOUND,
COUNT_INTERNAL_INBOUND,
COUNT_ANSWERED_INTERNAL_INBOUND,
COUNT_UNANSWERED_INTERNAL_INBOUND;
@Override
public String getSomething(Any any) {
return null;
}
}
我认为在这种情况下,这比在接口中创建默认方法更好,因为默认实现似乎主要与枚举有关,而不是与接口的所有其他实现者有关。
答案 2 :(得分:-1)
没有捷径可做。