方法引用其实就是方法调用,符号是两个冒号::来表示,左边是对象或类,右边是方法。它其实就是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新特性之方法引用的更多相关文章

  1. 乐字节-Java8新特性之方法引用

    上一篇小乐介绍了<Java8新特性-函数式接口>,大家可以点击回顾.这篇文章将接着介绍Java8新特性之方法引用. Java8 中引入方法引用新特性,用于简化应用对象方法的调用, 方法引用 ...

  2. Java 8新特性-4 方法引用

    对于引用来说我们一般都是用在对象,而对象引用的特点是:不同的引用对象可以操作同一块内容! Java 8的方法引用定义了四种格式: 引用静态方法     ClassName :: staticMetho ...

  3. Java8新特性之方法引用&Stream流

    Java8新特性 方法引用 前言 什么是函数式接口 只包含一个抽象方法的接口,称为函数式接口. 可以通过 Lambda 表达式来创建该接口的对象.(若 Lambda 表达式抛出一个受检异常(即:非运行 ...

  4. JDK8新特性04 方法引用与构造器引用

    import java.io.PrintStream; import java.util.Comparator; import java.util.function.*; /** * 一.方法引用 * ...

  5. 2020你还不会Java8新特性?方法引用详解及Stream 流介绍和操作方式详解(三)

    方法引用详解 方法引用: method reference 方法引用实际上是Lambda表达式的一种语法糖 我们可以将方法引用看作是一个「函数指针」,function pointer 方法引用共分为4 ...

  6. Java8新特性 -- Lambda 方法引用和构造器引用

    一. 方法引用: 若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用” 要求 方法的参数和返回值类型 和 函数式接口中的参数类型和返回值类型保持一致. 主要有三种语法格式: 对象 :: ...

  7. JDK8新特性之方法引用

    什么是方法引用 方法引用是只需要使用方法的名字,而具体调用交给函数式接口,需要和Lambda表达式配合使用. 如: List<String> list = Arrays.asList(&q ...

  8. Java8新特性之方法引用

    <Java 8 实战>学习笔记系列 定义 方法引用让你可以重复使用现有的方法定义,并像Lambda一样传递它,可以把方法引用看作针对仅仅涉及单一方法的Lambda的语法糖,使用它将减少自己 ...

  9. Java(43)JDK新特性之方法引用

    作者:季沐测试笔记 原文地址:https://www.cnblogs.com/testero/p/15228461.html 博客主页:https://www.cnblogs.com/testero ...

随机推荐

  1. 个人知识管理系统Version1.0开发记录(02)

    第 一 步 做 什 么 我们该如何入手呢?先来看看目前常用的三个方法. 1.从事物产生的源头出发,层层推进,步步验证,最后开花结果.这种方法经常用于科研项目,或者三期以后的工程,国家政府项目用的较多. ...

  2. 原生javascript-Tab选项卡-面向对象

    分析个人用原生JS获取类名元素的代码: getByClassName:function(className,parent){ var elem = [], node = parent != undef ...

  3. RabbitMQ消息队列(十)RPC应用2

    基于RabbitMQ RPC实现的主机异步管理 地址原文:http://blog.51cto.com/baiying/2065436,作者大大,我把原文贴出来了啊.不要告我 root@ansible: ...

  4. vue项目搭建 (一)

    vue项目搭建 (一) 由于一直想要有自己的框架,因而一直在尝试搭建各类结构,结合vue官网及git上大神bailicangdu的项目,再看看网上一些意见,及个人思考,总结的一些,不到之处希望大家可以 ...

  5. 1.spring cloud eureka server配置

    IDEA版本 2017.2.5 JDK 1.8 红色加粗内容为修改部分 1.创建一个新项目 2.选择eureka依赖 3.版本选择(重要)并且更新依赖 <?xml version="1 ...

  6. 使用群晖NAS:配置Git server

    1.首先在群晖的DSM的控制面板中创建一个用户例如是Git_test(我给了管理员权限) 2.在套件中心安装 Git server 3.打开Git server 勾选用户 Git_test 4.在控制 ...

  7. C++进阶2. typedef用法

    C++ 中的typedef用法 20131011 Typedef在C++中是一个关键字,他的用法有多重,但是自己又说不全面,所以整理一下: 1.用类型的别名 typedef char* PChar; ...

  8. Netlink 基础知识

    Netlink 基础知识 Netlink 相对于系统调用,ioctl 以及 /proc 文件系统而言具有以下优点: 1. 用户仅需要在 include/linux/netlink.h 中增加一个新类型 ...

  9. TF随笔-10

    #!/usr/bin/env python# -*- coding: utf-8 -*-import tensorflow as tf x = tf.constant(2)y = tf.constan ...

  10. java读取resource/通过文件名获取文件类型

    java读取resource java读取resource目录下文件的方法: 借助Guava库的Resource类 Resources.getResource("test.txt" ...