没有双冒号的Java 8供应商

时间:2015-08-16 23:08:32

标签: java java-8 java-stream

如果不使用:: notation,我无法创建供应商。所有教程似乎都在使用::来获取方法。

Function<String, Object> beanFactory = m_context::getBean;
Function<Void, IRCPublic> ircPublicSupplier = a -> (IRCPublic) beanFactory.apply("developerPublicConnection");
ircPublicSupplier.apply(null);

我如何将第2行转换为单行语句来创建供应商,并且只需使用&#39; .get()&#39; 。我可以使用&#39; .apply(null)&#39;但这看起来很脏。

谢谢!

2 个答案:

答案 0 :(得分:5)

Intellij救援。我把它定义为很长的路:

Supplier<IRCPublic> ircPublicSupplier = new Supplier<IRCPublic>() {
        @Override
        public IRCPublic get() {
            return (IRCPublic) beanFactory.apply("developerPublicConnection");
        }
    };

Intellij将其缩短为:

Supplier<IRCPublic> ircPublicSupplier = () -> (IRCPublic) beanFactory.apply("developerPublicConnection");

答案 1 :(得分:3)

你可以内联:

Supplier<IRCPublic> ircPublicSupplier = 
    () -> (IRCPublic) beanFactory.apply("developerPublicConnection");

或者您也可以在方法中包装IRCPublic返回的beanFactory实例:

IRCPublic getIrcPublic() {
    return (IRCPublic) beanFactory.apply("developerPublicConnection");
}

然后使用::

Supplier<IRCPublic> ircPublicSupplier = this::getIrcPublic;

这假定上面的行与定义getIrcPublic方法的同一类。