首页 > 解决方案 > 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)

但是这样它不会编译。请问有什么建议吗?

标签: javastaticsupplier

解决方案


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);
 }

这样做的好处是,如果您稍后添加新颜色,您不会忘记更新地图,因为如果您不这样做,编译器会报错。


推荐阅读