java 8中构造函数引用有什么用 [英] What are the uses of constructor reference in java 8

查看:36
本文介绍了java 8中构造函数引用有什么用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关 Java 8 功能的信息,这使我想到了这个 文章 ,我想知道构造函数引用的实际用途,我的意思是为什么不直接使用 new Obj ?

I was reading about Java 8 features, which lead me to this article and I was wondering about the actual uses of constructor reference, I mean why not just use new Obj ?

P.S,我试过谷歌搜索,但我没有找到有意义的东西,如果有人有代码示例、链接或啧啧,那就太好了

P.S, I tried googling, but I failed to find something meaningful, if someone has a code example, link or tut it will be great

推荐答案

首先,你应该明白构造函数引用只是方法引用的一种特殊形式.方法引用的要点在于它们不调用被引用的方法,而是提供了一种定义函数的方法,该函数将在被评估时调用该方法.

First of all, you should understand that constructor references are just a special form of method references. The point about method references is that they do not invoke the referenced method but provide a way to define a function which will invoke the method when being evaluated.

链接文章的示例可能看起来没有那么有用,但这是简短的自包含示例代码的普遍问题.这与hello world"程序相同.这并不比直接在控制台中输入文本hello world"有用,但无论如何都不是.它的目的是演示编程语言.

The linked article’s examples might not look that useful but that’s the general problem of short self-contained example code. It’s just the same as with the "hello world" program. It’s not more useful than typing the text "hello world" directly into the console but it’s not meant to be anyway. It’s purpose is to demonstrate the programming language.

正如 assylias 所示,有些用例涉及已经存在的功能接口使用JFC API.

As assylias has shown, there are use cases involving already existing functional interfaces using the JFC API.

关于将与构造函数引用一起使用的自定义函数式接口的用处,您必须考虑一般使用(函数式)interface 的原因:abstraction.

Regarding the usefulness of a custom functional interface that’ll be used together with a constructor reference, you have to think about the reason to use (functional) interface in general: abstraction.

由于接口的目的是抽象底层操作,用例是您不想执行无条件new SomeType的地方(…) 操作.

Since the purpose of an interface is to abstract the underlying operation, the use cases are the places where you do not want to perform an unconditional new SomeType(…) operation.

所以一个例子是众所周知的Factory模式,你定义一个interface来构造一个对象,而通过构造函数引用实现工厂只是一个em> 选择出无限的可能性.

So one example is the commonly known Factory pattern where you define an interface to construct an object and implementing the factory via constructor reference is only one option out of the infinite possibilities.

另一个重要的点是所有类型的泛型方法,在这些方法中,需要构造类型实例的可能性,这是由于类型擦除而未知的.它们可以通过作为参数传递的函数来实现,并且是否需要现有的功能接口之一,或者需要自定义接口,这仅取决于所需的参数数量和类型.

Another important point are all kinds of Generic methods where the possibility to construct instances of the type, that is not known due to type erasure, is needed. They can be implemented via a function which is passed as parameter and whether one of the existing functional interfaces fits or a custom one is needed simply depends on the required number and types of parameters.

这篇关于java 8中构造函数引用有什么用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆