如何编写Java 8 Consumer来使用Consumer的Collection(Map)

时间:2017-09-28 08:46:21

标签: interface java-8 consumer

我在Java中有Java消费者列表,我在HashMap中维护,但是当我调用accept方法时,参数将变为null。

    private ObjectMapper objectMapper;
    Map<String, Consumer<String>> daoMethodMap = new HashMap<>();

    daoMethodMap.put("CLASS1", ( serializedRecord ) -> {
            try
            {
                Class1 class1Obj = objectMapper.readValue(serializedRecord, Class1.class);
                Class1Dao.insertClass1Instance(class1Obj);
            }
            catch( Exception e )
            {
                throw new RuntimeExeption(e);
            }

        });

        daoMethodMap.put("CLASS2", ( serializedRecord ) -> {
            try
            {
                Class2 class2Obj = objectMapper.readValue(serializedRecord, Class2.class);
                Class2Dao.insertClass2Instance(class2Obj);
            }
            catch( Exception e )
            {
                throw new RuntimeExeption(e);
            }

        });

        daoMethodMap.put("CLASS3", ( serializedRecord ) -> {
            try
            {
                Class3 class3Obj = objectMapper.readValue(serializedRecord, Class3.class);
                Class3Dao.insertClass3Instance(class3Obj);
            }
            catch( Exception e )
            {
                throw new RuntimeExeption(e);
            }

        });

当我调用任何消费者时,消费者中的参数似乎什么也没有,所以我使用具有所有属性作为空值的objectmapper来获得重建对象。你们有什么想法吗?

这就是我所说的Consumer-

Consumer<String> daoMethod = daoMethodMap.get("CLASS1");
String record = "{\"prop1\":\"val1\", \"prop2\":\"val2\"}";
daoMethod.accept(record);

在Consumer,我得到class1Obj,其值为prop1,prop2为null。

0 个答案:

没有答案