本文介绍了Java8 Lambdas 与匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 Java8 最近发布并且其全新的 lambda 表达式看起来非常酷,我想知道这是否意味着我们习惯的匿名类的消亡.

Since Java8 has been recently released and its brand new lambda expressions looks to be really cool, I was wondering if this means the demise of the Anonymous classes that we were so used to.

我对此进行了一些研究,并找到了一些关于 Lambda 表达式如何系统地替换这些类的很酷的示例,例如 Collection 的 sort 方法,该方法用于获取 Comparator 的匿名实例来执行排序:

I've been researching a bit about this and found some cool examples about how Lambda expressions will systematically replace those classes, such the Collection's sort method, which used to get an Anonymous instance of Comparator to perform the sort:

Collections.sort(personList, new Comparator<Person>(){
  public int compare(Person p1, Person p2){
    return p1.firstName.compareTo(p2.firstName);
  }
});

现在可以使用 Lambda 来完成:

Now can be done using Lambdas:

Collections.sort(personList, (Person p1, Person p2) -> p1.firstName.compareTo(p2.firstName));

而且看起来非常简洁.所以我的问题是,是否有任何理由继续在 Java8 中使用这些类而不是 Lambdas?

And looks surprisingly concise. So my question is, is there any reason to keep using those classes in Java8 instead of Lambdas?

编辑

同样的问题,但方向相反,使用 Lambdas 代替匿名类有什么好处,因为 Lambdas 只能与单一方法接口一起使用,这个新功能是仅在少数情况下使用的快捷方式还是真的有用吗?

Same question but in the opposite direction, what are the benefits of using Lambdas instead of Anonymous classes, since Lambdas can only be used with single method interfaces, is this new feature only a shortcut only used in few cases or is it really useful?

推荐答案

匿名内部类 (AIC) 可用于创建抽象类或具体类的子类.AIC 还可以提供接口的具体实现,包括添加状态(字段).可以在其方法主体中使用 this 引用 AIC 的实例,因此可以在其上调用更多方法,其状态可以随时间变化等.这些都不适用于 lambda.

An anonymous inner class (AIC) can be used to create a subclass of an abstract class or a concrete class. An AIC can also provide a concrete implementation of an interface, including the addition of state (fields). An instance of an AIC can be referred to using this in its method bodies, so further methods can be called on it, its state can be mutated over time, etc. None of these apply to lambdas.

我猜想 AIC 的大部分用途是提供单个函数的无状态实现,因此可以用 lambda 表达式替换,但是 AIC 的其他用途不能使用 lambda.AIC 将继续存在.

I'd guess that the majority of uses of AICs were to provide stateless implementations of single functions and so can be replaced with lambda expressions, but there are other uses of AICs for which lambdas cannot be used. AICs are here to stay.

更新

AIC 和 lambda 表达式之间的另一个区别是 AIC 引入了一个新的作用域.也就是说,名称是从 AIC 的超类和接口解析出来的,并且可以隐藏出现在词法封闭环境中的名称.对于 lambda,所有名称都按词法解析.

Another difference between AICs and lambda expressions is that AICs introduce a new scope. That is, names are resolved from the AIC's superclasses and interfaces and can shadow names that occur in the lexically enclosing environment. For lambdas, all names are resolved lexically.

这篇关于Java8 Lambdas 与匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 04:36