java - Java如何在地图中存储getter
问题描述
我想通过给定的枚举调用动态吸气剂。我想在静态地图中定义它。但我不确定我的对象将如何使用该方法。
我有颜色枚举和对象库。
public enum Color {
Red,
Blue,
Black,
Green,
Pink,
Purple,
White;
}
public class Library{
public List<String> getRed();
public List<String> getBlue();
public List<String> getBlack();
.....
}
我想要一个 Map ,所以当我有一个按类型的新库对象时,我会调用正确的 get。例如 :
private static Map<Color, Function<......>, Consumer<....>> colorConsumerMap = new HashMap<>();
static {
colorConsumerMap.put(Color.Red, Library::getRed);
colorConsumerMap.put(Color.Blue, Library::getBlue);
}
Library lib = new Library();
List<String> redList = colorConsumerMap.get(Color.Red).apply(lib)
但是这样它不会编译。请问有什么建议吗?
解决方案
Function 接口有两个类型参数:输入类型(Library
在您的情况下)和输出类型(List<String>
在您的情况下)。因此,您必须将地图的类型更改为Map<Color, Function<Library, List<String>>
.
但是,请考虑将逻辑不是放在地图中,而是放在枚举值本身中。例如:
public enum Color {
Red(Library::getRed),
Blue(Library::getBlue);
private Function<Library, List<String>> getter;
private Color(Function<Library, List<String>> getter) {
this.getter = getter;
}
public List<String> getFrom(Library library) {
return getter.apply(library);
}
}
public class Library{
public List<String> getRed() { return Collections.singletonList("Red"); }
public List<String> getBlue() { return Collections.singletonList("Blue"); }
}
Library lib = new Library();
System.out.println(Color.Red.getFrom(lib));
System.out.println(Color.Blue.getFrom(lib));
或者,如果您不想使用 Java 8 功能:
public enum Color {
Red {
List<String> getFrom(Library library) {
return library.getRed();
}
},
Blue {
List<String> getFrom(Library library) {
return library.getBlue();
}
};
abstract List<String> getFrom(Library library);
}
这样做的好处是,如果您稍后添加新颜色,您不会忘记更新地图,因为如果您不这样做,编译器会报错。
推荐阅读
- r - R中具有非等间距值的二维线性插值
- javascript - Ember Octane (3.22+) 为什么使用 {{on 'click' this.function}} 而不是 onclick={{this.function}}
- docker - OpenShift 上的 pgAdmin 使用 RedHat 基本映像
- postgresql - knex / postgresql 将外键更新为空
- docker - Docker 桌面吃掉所有内存并崩溃
- powershell - 用返回的变量替换单元格值的问题 - 格式不正确?
- reactjs - 这可能不是 npm 的问题。上面可能有额外的日志输出。退出状态 1
- django - 如何在 Django 路径中创建项目
- python - 在 QLineEdit 对象 PyQt5 上设置验证器
- backend - 客户端和服务器端渲染的区别