问题描述
我的应用程序中有3个枚举器类.这3个类都有2个重复的方法,我们希望在实现的每个枚举中都可以使用它们.
I have 3 enumerator classes in my application. All 3 classes have 2 duplicate methods that we want available in every enum that we implement.
public static List<String> supported(){
return Arrays.asList([[EnumClass]].values())
.stream().map(Enum::name).collect(Collectors.toList());
}
public static boolean contains(String value){
boolean response = false;
try {
response = value != null ? [[EnumClass]].valueOf(value.trim().toUppercase()) != null : false;
} catch (Exception e){
LOGGER.error("ERROR: {}", e);
}
return response;
}
这些方法中唯一更改的部分是 EnumClass ,它是每个枚举的类.
The only part of these methods that changes is the EnumClass which is the class of each enum.
第一个方法将打印枚举类的所有可能值,第二个方法如果可以将给定的String制成枚举类,则返回true/false.
The first method will print all the possible values for the enum class and the second method will return true/false if the given String can be made into the enum class.
我试图实现实现这些方法的接口,但是我不能使用values(),因为它不是Enum API的一部分.我不能将这些方法与每个类特别相关,因为这些方法是公共静态的.由于Java不支持多重继承,因此无法创建自定义类并扩展Enum来扩展它.
I tried to implement an Interface that implemented these methods, but I can't use values() because it's not part of the Enum API. I can't relate the methods to each class specifically because the methods are public static. I can't create a custom class and extend Enum to extend that since Java doesn't support multiple inheritance.
与此同时,我的代码可以正常工作,但是重复确实困扰着我,我觉得它可以做得更好.如果我们继续添加新的枚举数,那么重复将变得更糟.
For the meanwhile I have my code working, but the duplication really bothers me and I feel like it can be way better. If we continue to add new enumerators then the duplication will just get worse.
推荐答案
您不能让Enum类实现接口,但是可以在每个枚举上保留对对象的静态引用,并且这些对象可以实现公共接口.这样可以减少重复的次数.
You cannot have the Enum class implement an interface, but you can keep a static reference to an object on each enum, and those objects can implement a common interface. This will reduce the amount of duplication.
public static class EUtils<E extends Enum<E>> {
private final E[] values;
private Function<String,E> valueOf;
public EUtils(E[] values, Function<String,E> valueOf) {
this.values = values;
this.valueOf = valueOf;
}
public List<String> supported(){
return Arrays.asList(values)
.stream().map(Enum::name).collect(Collectors.toList());
}
public boolean contains(String value){
boolean response = false;
try {
response = value != null ? valueOf.apply(value.trim().toUpperCase()) != null : false;
} catch (Exception e){
e.printStackTrace();
}
return response;
}
}
private enum Directions {
LEFT,
RIGHT;
public static EUtils<Directions> enumUtils = new EUtils<>(Directions.values(),Directions::valueOf);
}
public static void main(String[] args) {
System.out.println(Directions.enumUtils.contains("LEFT"));
System.out.println(Directions.enumUtils.contains("X"));
}
这篇关于如何在Java 8中用Enums重用重复代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!