4

我想通过给定的枚举调用动态吸气剂。我想在静态地图中定义它。但我不确定我的对象将如何使用该方法。

我有颜色枚举和对象库。

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)

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

4

3 回答 3

1

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

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

于 2018-07-11T11:51:48.267 回答
1

看起来您Map应该声明为:

private static Map<Color, Function<Library,List<String>> colorConsumerMap = new HashMap<>()

因为你的吸气剂回来了List<String>

于 2018-07-11T11:34:23.423 回答
1

您好,请为供应商找到以下代码:-

enum Color {
    Red,
    Blue,
    Black,
    Green,
    Pink,
    Purple,
    White;
}

class Library{
    public Supplier supplier;
      public List<String> getRed(){};   // implement according to need 
      public List<String> getBlue(){};  // implement according to need 
      public List<String> getBlack(){}; // implement according to need 
    private  Map<Color, Supplier<List<String>>> colorConsumerMap = new HashMap<Color, Supplier<List<String>>>();
    static {
        colorConsumerMap.put(Color.Red,  Library::getRed);
        colorConsumerMap.put(Color.Blue,  Library::getBlue);
    }

这里我们使用的是 java 8 supplier

要从中获取值,HashMap请使用代码:-

Supplier getMethod  = colorConsumerMap.get(Color.Red);
List<String> values = getMethod.get();
于 2018-07-11T11:37:09.437 回答