具有完整构造函数调用的方法引用,作为Java中的lambda表达式 [英] Method reference with a full constructor call as a lambda expression in Java

查看:191
本文介绍了具有完整构造函数调用的方法引用,作为Java中的lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不久前遇到了一个竞争性答案,比我的使用一个全新的方法引用更好代替lambda.

I have encountered a short time ago with a competitive answer better than mine that uses a quite new method reference to me as replacement of lambda.

Stream.generate(new AtomicInteger(1)::getAndIncrement)...

我查看了有关方法引用的Oracle规范,并且定义了4种类型:

I looked the Oracle specifications about the Method references and there are defined 4 types:

  • 引用静态方法ContainingClass::staticMethodName
  • 引用特定对象的实例方法containingObject::instanceMethodName
  • 对特定类型ContainingType::methodName
  • 的任意对象的实例方法的引用
  • 对构造函数的引用ClassName::new
  • Reference to a static method ContainingClass::staticMethodName
  • Reference to an instance method of a particular object containingObject::instanceMethodName
  • Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName
  • Reference to a constructor ClassName::new

我很难对这一分类.我还没有找到关于SO的任何问题,也没有找到文档中说明的任何相关问题.它将如何转换为匿名类?

I struggle with categorizing this one. I haven't found any question on SO or anything relevant explained in the docs. How would be this translated to an anonymous class?

我的怀疑是:

IntStream.generate(new IntSupplier() {

    AtomicInteger atom = new AtomicInteger(1);

    @Override
    public int getAsInt() {
        return atom.getAndIncrement();
    }
})....

...我不知道这怎么可能.乍一看,我猜这是这样的:

... I don't understand how is this possible. At first sight, I would guess the expression is:

IntStream.generate(new IntSupplier() {

    @Override
    public int getAsInt() {
        return new AtomicInteger(1).getAndIncrement();
    }
})....

...但这只是() -> new AtomicInteger(1).getAndIncrement().

在哪里定义了这种表达式,以及如何在lambda/anonymous类中将其完全重写?

Where is this kind of expression defined and how it exactly would be rewritten in the lambda/anonymous class?

推荐答案

那么new AtomicInteger(1)返回一个实例,因此它是第二个实例.有关如何翻译的确切详细信息是特定于实现的,但是它是创建的单个实例,并且由

Well new AtomicInteger(1) returns an instance, so it's the second one. The exact details of how this is translated are implementation specific, but it's a single instance created and this is back-ed up by the JLS 15.13.3

首先,如果方法引用表达式以ExpressionName或Primary开头,则将评估该子表达式

First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated

简而言之,::之前的部分在首次遇到其声明时被评估 .

In plain english, the part before :: is evaluated when it's declaration is first encountered.

您的假设如何转换几乎是正确的,就像在函数本身之外生成实例并使用该实例一样-由于它实际上是最终的,因此是允许的.

Your assumption how this is translated is almost correct, it's like generating an instance outside of the function itself and using that - since it is effectively final, this is permitted.

这篇关于具有完整构造函数调用的方法引用,作为Java中的lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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