jdk1.8新特性之方法引用
方法引用其实就是方法调用,符号是两个冒号::来表示,左边是对象或类,右边是方法。它其实就是lambda表达式的进一步简化。如果不使用lambda表达式,那么也就没必要用方法引用了。啥是lambda,参见jdk1.8新特性之lambda表达式。看实际例子:
先看函数式接口:
@FunctionalInterface
public interface CompositeServiceMethodInvoker<M extends Message, R extends Message>
{ Logger LOGGER = LoggerFactory.getLogger(CompositeServiceMethodInvoker.class); ApiResult<M> invoke(InvokeContext ic, R r); default M getCompositeResponse(R request)
throws PortalException
{
return getCompositeResponse(GetSpringContext.getInvokeContext(), request);
} default M getCompositeResponse(InvokeContext invokeContext, R request)
throws PortalException
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(
"Enter CompositeServiceEngine.getCompositeResponse(), identityId:{}, requestClassName:{}, request:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request));
} ApiResult<M> apiResult = invoke(invokeContext, request); if (Util.isEmpty(apiResult))
{
LOGGER.error(
" CompositeServiceEngine.getCompositeResponse(), Call microservice error, return null, identityId:{}," +
" requestClassName:{}, request:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request));
throw new PortalException(MSResultCode.MICROSERVICE_RETURN_NULL,
(" CompositeServiceEngine.getCompositeResponse(), Call microservice error, return null, " +
"requestClassName:")
.concat(request.getClass().getName()));
} int code = apiResult.getCode();
if (!apiResult.isSuccess())
{
LOGGER.error(
"Call CompositeServiceEngine.getCompositeResponse() error, identityId:{}, requestClassName:{}, " +
"request:{}, return code:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request),
code);
throw new PortalException(code,
"Call CompositeServiceEngine.getCompositeResponse() error, requestClassName:".concat(request.getClass()
.getName()));
}
else
{
M response = apiResult.getData(); if (Util.isEmpty(response))
{
LOGGER.error(
"Call CompositeServiceEngine.getCompositeResponse() error,return null, identityId:{}, " +
"requestClassName:{}, request:{}, return code:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request),
code);
throw new PortalException(code,
"Call CompositeServiceEngine.getCompositeResponse() error, return null, requestClassName:".concat(
request.getClass().getName()));
} if (LOGGER.isDebugEnabled())
{
LOGGER.debug(
"Exit CompositeServiceEngine.getCompositeResponse(), identityId:{}, requestClasssName:{}, " +
"request:{}, result:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request),
JsonFormatUtil.printToString(response));
}
return response;
}
} default String getCompositeResponseCode(R request)
throws PortalException
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(
"Enter CompositeServiceEngine.getCompositeResponse() , identityId:{}, requestClassName:{}, request:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request));
} ApiResult<M> apiResult = invoke(GetSpringContext.getInvokeContext(), request); if (Util.isEmpty(apiResult))
{
LOGGER.error(
" CompositeServiceEngine.getCompositeResponse(), Call microservice error, return null, " +
"identityId:{}, requestClassName:{}, request:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
JsonFormatUtil.printToString(request));
throw new PortalException(MSResultCode.MICROSERVICE_RETURN_NULL,
(" CompositeServiceEngine.getCompositeResponse(), Call microservice error, return null, " +
"requestClassName:{}")
.concat(request.getClass().getName()));
} int code = apiResult.getCode(); if (LOGGER.isDebugEnabled())
{
LOGGER.debug(
"Exit CompositeServiceEngine.getCompositeResponse(), identityId:{}, requestClassName:{}, result:{}",
CommonHttpUtil.getIdentity(),
request.getClass().getName(),
code);
}
return String.valueOf(code);
} }
这里有3个默认方法,一个抽象方法,抽象方法返回对象ApiResult<M>。我们来看看如果用匿名内部类怎么写:
CompositeServiceMethodInvoker<GetBookFeeDescResponse, GetBookFeeDescRequest> getBooFeeDescMethodInvoker =
new CompositeServiceMethodInvoker<GetBookFeeDescResponse, GetBookFeeDescRequest>(){ public ApiResult<GetBookFeeDescResponse> invoke(InvokeContext context, GetBookFeeDescRequest request)
{
ServiceController controller = createRpcController("getBookFeeDesc", context);
ApiResult<GetBookFeeDescResponse> result = new ApiResult<GetBookFeeDescResponse>(controller);
stub.getBookFeeDesc(controller, request, result);
return result;
}};
注意这里的泛型已经用具体类型替换了。如果我们使用lambda表达式,那么可以这么写:
CompositeServiceMethodInvoker<GetBookFeeDescResponse, GetBookFeeDescRequest> getBooFeeDescMethodInvoker =
(InvokeContext context, GetBookFeeDescRequest request) -> {
ServiceController controller = createRpcController("getBookFeeDesc", context);
ApiResult<GetBookFeeDescResponse> result = new ApiResult<GetBookFeeDescResponse>(controller);
stub.getBookFeeDesc(controller, request, result);
return result;
};
现在再来看这样一种情况,如果我们刚好在某个类中已经实现了lambda所指代的代码块,比如有这么一个类BookProductConsumer:
public class BookProductConsumer
extends ServiceConsumer
{ public ApiResult<GetBookFeeDescResponse> getBookFeeDesc(InvokeContext context,
GetBookFeeDescRequest request) {
ServiceController controller = createRpcController("getBookFeeDesc",context);
ApiResult<GetBookFeeDescResponse> result = new ApiResult<GetBookFeeDescResponse>(controller);
stub.getBookFeeDesc(controller, request, result);
return result;
}
}
这里的getBookFeeDesc方法返回了ApiResult对象(这里接口里的泛型M已经具体为GetBookFeeDescResponse对象了)。我们可以看到,变量getBooFeeDescMethodInvoker所指代的方法块已经定义在了BookProductConsumer类的getBookFeeDesc方法中,所以使用方法引用来替换原来的lambda表达式:
CompositeServiceMethodInvoker<GetBookFeeDescResponse, GetBookFeeDescRequest> getBooFeeDescMethodInvoker = BookProductConsumer::getBookFeeDesc;
这就是类的方法引用,根据方法调用的不同情况,还有对象的方法引用、类的静态方法引用、类的构造方法引用。
jdk1.8新特性之方法引用的更多相关文章
- 乐字节-Java8新特性之方法引用
上一篇小乐介绍了<Java8新特性-函数式接口>,大家可以点击回顾.这篇文章将接着介绍Java8新特性之方法引用. Java8 中引入方法引用新特性,用于简化应用对象方法的调用, 方法引用 ...
- Java 8新特性-4 方法引用
对于引用来说我们一般都是用在对象,而对象引用的特点是:不同的引用对象可以操作同一块内容! Java 8的方法引用定义了四种格式: 引用静态方法 ClassName :: staticMetho ...
- Java8新特性之方法引用&Stream流
Java8新特性 方法引用 前言 什么是函数式接口 只包含一个抽象方法的接口,称为函数式接口. 可以通过 Lambda 表达式来创建该接口的对象.(若 Lambda 表达式抛出一个受检异常(即:非运行 ...
- JDK8新特性04 方法引用与构造器引用
import java.io.PrintStream; import java.util.Comparator; import java.util.function.*; /** * 一.方法引用 * ...
- 2020你还不会Java8新特性?方法引用详解及Stream 流介绍和操作方式详解(三)
方法引用详解 方法引用: method reference 方法引用实际上是Lambda表达式的一种语法糖 我们可以将方法引用看作是一个「函数指针」,function pointer 方法引用共分为4 ...
- Java8新特性 -- Lambda 方法引用和构造器引用
一. 方法引用: 若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用” 要求 方法的参数和返回值类型 和 函数式接口中的参数类型和返回值类型保持一致. 主要有三种语法格式: 对象 :: ...
- JDK8新特性之方法引用
什么是方法引用 方法引用是只需要使用方法的名字,而具体调用交给函数式接口,需要和Lambda表达式配合使用. 如: List<String> list = Arrays.asList(&q ...
- Java8新特性之方法引用
<Java 8 实战>学习笔记系列 定义 方法引用让你可以重复使用现有的方法定义,并像Lambda一样传递它,可以把方法引用看作针对仅仅涉及单一方法的Lambda的语法糖,使用它将减少自己 ...
- Java(43)JDK新特性之方法引用
作者:季沐测试笔记 原文地址:https://www.cnblogs.com/testero/p/15228461.html 博客主页:https://www.cnblogs.com/testero ...
随机推荐
- filter-mapping中的dispatcher使用
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABGAAAAEJCAIAAABUr8bLAAAgAElEQVR4nO3dX2/bVoL3cb4h+WYnwN
- JS种正则表达式的基础用法
基础语法 元字符 常用元字符 含义 . 匹配除换行符以外的任意字符 \w 匹配字母数字或下划线 \W 匹配不是字母.数字.下划线的字符 \d 匹配数字,相当于[0-9] \D 匹配不是数字的字符 \s ...
- scala学习之实现RPC通信
最近学习scala,个人感觉非常灵活,实现rpc通信非常简单,函数式编程比较烧脑 1.搭建工程 创建scala maven 工程 项目pom文件 <project xmlns="htt ...
- kibana安装
kibana,ELK中的K,主要为ES提供界面化操作,据说还是比较炫的,今天安装5.5.2版本进行尝试一把. 安装过程不难,简单的配置了一下端口和IP即可,难度不大. config下的kibana.y ...
- The capacitive screen technology - tadpole
- [置顶]
滴滴插件化VirtualAPK框架原理解析(二)之Service 管理
在前一篇博客滴滴插件化框架VirtualAPK原理解析(一)之插件Activity管理 中VirtualAPK是如何对Activity进行管理的,本篇博客,我们继续来学习这个框架,这次我们学习的是如何 ...
- js 以函数名作为参数动态执行 函数
function myFunc() { console.log(11111); } test("myFunc"); function test(funcName) { if(typ ...
- UICollectionView 数据库元素分组 多种section分开显示
第一遍 复杂方法 : 数据库查询一个表中userID 然后进行分类 中间去重 获得ID个数 放到section 中 显示 #pragma mark - 查询不同的ID 各数 - (void)c ...
- Xcode5.1.1支持低版本和image not found和Couldn't register XXXX with the bootstrap server. Error: unknown error code.
一:问题 targets中证书的设置 1.项目支持多设备(Xcode5.1.1支持低版本) 2.真机测试要确保Code Siging 设置没问题 支持的最低版本 二 :问题:image not f ...
- Python3 移动文件——合集
文件/文件夹操作头文件 import os import shutil 参考 Python3批量移动指定文件到指定文件夹