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 ...
 
随机推荐
- Ansible 小手册系列 八(Yaml 语法格式)
			
YAML 语言(发音 /ˈjæməl/ )的设计目标,就是方便人类读写.它实质上是一种通用的数据串行化格式. 它的基本语法规则如下. • 大小写敏感 • 使用缩进表示层级关系 • 缩进时不允许使用Ta ...
 - iptables疑问总结(一)
			
1.关于-j 的return说明 1. 从一个CHAIN里可以jump到另一个CHAIN, jump到的那个CHAIN是子CHAIN.2. 从子CHAIN return后,回到触发jump的那条规则, ...
 - VB与C#的区别(转载)
			
由于工作原因要熟悉这两门编程语言.网上找的. VB.NET Program Structure C# Imports System Namespace Hello Clas ...
 - 【51nod-1091】线段的重叠(贪心)
			
所有线段按起点从小到大排序,然后比较出最大的重叠部分.比如第i条线段和第j条线段进行比较找出重叠部分(j>i),当第j条线段的右端点<第i条线段的右端点,此时可以让i继续比较后面的线段:如 ...
 - Java--------------Windows下Redis的安装使用
			
摘要 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted s ...
 - Easyui datagrid自定义排序
			
做项目遇到个关于排序问题,想着在前端排序,正好Easyui有这个功能,所以就拿来用了一下,因为跟官网的Demo不太一样,所以总结一下: 首先这一列是要排序的列(当然,在生产环境,这一列是隐藏的,在开发 ...
 - 联想北研实习生面试-嵌入式Linux研发工程师
			
8月中旬暑假去联想北研参加了实习生面试,面试职位是嵌入式Linux研发工程师.投完简历第二天,主管回复我邮件,意思是说随时来面试,到北研时候给他打个电话就行.于是我回复条短信表示感谢,并约好时间第二天 ...
 - set类型以及其操作
			
sets类型 sets类型以及操作Set是无序集合,它是string类型的无序集合.set是通过hash table实现的,添加.删除和查找的复杂度都是0(1).对集合我们可以取并集.交集.差集.通过 ...
 - Win10启动盘制作工具
			
Rufus https://rufus.akeo.ie/ http://www.iplaysoft.com/windows-10-udisk-install.html
 - Oracle解决中文乱码
			
原因 经过一番查证,发现问题的源头不是出现在PLSQL上,而是出现在我们的Oracle上,由于我们的Oracle数据库里的字符集不支持中文导致的,既然知道了原因,就好办了,我们就配置我们的Oracle ...