Java 8 Lambda Type Cast ------ (

2021-09-12  本文已影响0人  帕博雷克斯丢丢

Question:

下面的代码在干嘛?
getSpringFactoriesInstances(Bootstrapper.class).stream()
                .map((bootstrapper) -> ((BootstrapRegistryInitializer) bootstrapper::initialize))
                .forEach(initializers::add);

问点是这段:(bootstrapper) -> ((BootstrapRegistryInitializer) bootstrapper::initialize)

Answer:

对Lambda表达式bootstrapper::initialize进行转型;bootstrapperBootstrapper接口的实例,而BootstrapperFunctionalInterfaceBootstrapRegistryInitializer同样也是FunctionalInterface,所以转型后bootstrapper::initialize变为BootstrapRegistryInitializer::method类型;当然被转型的Lambda要和目标类型的Lambda是同一种FunctionalInterface,即两种类型的\color{red}{核心方法}\color{orange}{形参列表和返回值类型}要相同(方法名无所谓,但是这里其实是为了进行兼容性类型替换,所以要方法签名相同);比如Function<T, R>可以转为Function<T, R>,但不能转为Consumer<T>
\color{green}{总之,总结下来就是:} \color{red}{函数替换}
还有一点需要注意,那就是类型转换其实和\color{red}{函数替换}是一样一样的。
ps: 方法引用::也是Lambda
上一篇 下一篇

猜你喜欢

热点阅读