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 ...
随机推荐
- http请求的GET和POST请求:查询和新增(server.php)
<?php //设置页面内容是html编码格式是utf-8 header("Content-Type: text/plain;charset=utf-8"); //heade ...
- VS展开当前目录
- System.Zip
自XE2增加的System.Zip单元很好.注意事项: 1.文件压缩到文档后所使用的文件名会成为解压后的文件名,如果该文件名为指定文件名且无后缀名,那么解压出来的文件名也没有后缀名:
- java根据所给的根目录获取底下所有文件夹结构
所写工具类背景:项目经理叫我写个工具类实现:给个项目的根目录分析java文件及jsp文件.记录文件类型.路径.文件名和包名. 定义的实体类(这里我用了easypoi以后方便写入excel文档) @Da ...
- 重置input checked
<!-- 作者:duke 时间:2018-10-24 描述: 重置input 样式--> <!DOCTYPE HTML><html> <head> &l ...
- 01_StudentManager
package com.dao; import java.util.ArrayList; import java.util.Iterator; import java.util.List; impor ...
- Alpha冲刺一 (2/10)
前言 队名:拖鞋旅游队 组长博客:https://www.cnblogs.com/Sulumer/p/9960487.html 作业博客:https://edu.cnblogs.com/campus/ ...
- Confluence 安装
一.事前准备 1.jdk安装:5.8.10的jdk至少是7,其中7中还有很多官网是不建议的,这儿选中jdk-7u79 二.安装Confluence 双击atlassian-confluence-5.8 ...
- 解如何利用 XML 和 JavaScript Object Notation 在 Ajax 客户端和 Java 服务器之间传输数据(代码)(Oracle)。
---------------------------------ajaxUtil----------------------------------------------------------- ...
- SQL Server(MSSQLSERVER)启动失败,提示“请求失败或服务未及时响应
1.SQL Server(MSSQLSERVER)启动失败,提示“请求失败或服务未及时响应. --------------------------- SQL Server 配置管理器 -------- ...