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 ...
随机推荐
- 常用的SpringMVC注解
1.@RequestMapping() 访问链接编写: 例如: (1).请求方法: 访问链接: (2).请求参数和请求头: 访问链接: 2.@PathVariable 例如: 访问链接: 结果显示: ...
- Maven 中的dependencies与dependencyManagement的区别
1.dependencyManagement 在Maven中dependencyManagement的作用其实相当于一个对所依赖jar包进行版本管理的管理器 在pom.xml文件中,jar的版本判断的 ...
- iptables(五)iptables匹配条件总结之二(常用扩展模块)
iprange扩展模块 之前我们已经总结过,在不使用任何扩展模块的情况下,使用-s选项或者-d选项即可匹配报文的源地址与目标地址,而且在指定IP地址时,可以同时指定多个IP地址,每个IP用" ...
- Oracle11g创建表空间及用户
第1步:创建临时表空间 create temporary tablespace pgenius_temptempfile '/data/oracle/oradata/orcl/pgenius_te ...
- kvm虚拟主机安装速度很慢
在c6220 II上部署虚拟化遇到的问题: 1.部署完kvm后,安装虚拟主机的过程非常缓慢,但是最终能成功 原因:宿主机BIOS的virtualization technology设置为Disable ...
- C# 常用字符串处理办法
再基础的东西不常用的话就得记下来...不然就忘记了. C#字符串中特殊字符的转义 一个是双引号",另一个就是转义符\ 对于同样一个字符串:地址:"C:\Users\E.txt&qu ...
- MySQL学习(三): 初识数据表
打开数据库: USE db_name : 打开数据库. 创建数据表: 查看数据表: 查看数据表结构: 数据简单的插入与查找: 插入:INSERT [INTO] tbl_name [(col_name) ...
- PostgreSQL 9.6 同步多副本、remote_apply记录
摘自:https://yq.aliyun.com/articles/61274 同步多副本配置方法 参数配置如下 synchronous_standby_names (string) 支持两种写法 n ...
- windows7 下安装python3.6开发环境
所有的软件都放在百度云盘里: 链接: https://pan.baidu.com/s/1rux8sDK9thhbZ1qjwQg6kA 密码: iq4c 1. 安装python3.6.5 安装的时候要把 ...
- postgresql与Oracle:空字符串与null
空字符串:两个单引号,中间无空格等任何内容 在postgresql中,空字符串与null是不同的:而oracle中,空字符串与null等同.测试如下: postgresql中: postgres=# ...