java 8中构造函数的用法是什么? [英] What are the uses of constructor reference in java 8

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

问题描述

我正在阅读有关Java 8功能的内容,这些功能将我引导至文章,我想知道构造函数参考的实际用法,我的意思是为什么不使用 new Obj

PS,我尝试了谷歌搜索,但是我没有找到有意义的东西,如果有人有代码示例,链接或啧啧声将会很棒。首先,你应该明白构造函数引用只是方法引用的一种特殊形式。关于方法引用的一点是,它们不会调用被引用的方法,而是提供一种方法来定义一个函数,它在被评估时将调用该方法。



链接的文章示例可能看起来不太有用,但这是短自包含示例代码的一般问题。这和hello world程序一样。这并不比直接在控制台中输入文本hello world更有用,但它并不意味着无论如何。它的目的是演示编程语言。



由于 assylias显示 a>,有一些用例涉及使用JFC API的已有函数 interface s。






关于将与构造函数引用一起使用的自定义函数接口的用处,您必须考虑使用(函数式)接口接口的用途是: 抽象底层操作,用例是你不需要执行无条件 new SomeType(...)操作的地方。

>

所以一个例子就是众所周知的 Factory 模式,其中您定义了一个接口来构造一个对象并通过构造函数引用来实现工厂只是一个选项无论可能性如何。

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

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, 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.

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.

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


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.

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.

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天全站免登陆