在Session中使用lambda表达式 [英] Using a lambda expression in Session

查看:129
本文介绍了在Session中使用lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Javafx应用程序,其中使用JavaMail发送电子邮件。在创建新Session时,我使用语法。

I am writing a Javafx application in which an email is sent using JavaMail. When creating a new Session I use the syntax.

            Session session = Session.getInstance(props, 
            //Use labmda expression?
            new javax.mail.Authenticator() {

                protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
                return new javax.mail.PasswordAuthentication(userName, password);

                }
            }
        );

我想知道是否可以使用lambda表达式来简化它,例如

I was wondering if a lambda expression could be used to simplify that such as

() -> return new java.mail.PasswordAuthentiaction(userName, password)

但每当我使用它时会抛出不兼容的类型,并说Authenticator不是一个功能界面。

but whenever I use that it throws Incompatible types, and says that Authenticator isn't a functional interface.

推荐答案

不,你不能在这里使用lambda。 Lambdas只能用作功能接口实现的表示(只有一个抽象方法的接口),但 Authenticator 不是功能接口,因为

No, you can't use lambda here. Lambdas can be used only as representation of implementation of functional interface (interface with only one abstract method) but Authenticator is not functional interface because


  1. 它没有一个lambda应该实现的抽象方法(实际上它没有任何抽象方法)

  2. (摘要,但仍然)不是接口

  1. it doesn't have exactly one abstract method which lambda should implement (actually it doesn't have any abstract methods)
  2. it is class (abstract, but still class) not interface.

因此,lambdas只能用于具有一个抽象方法的接口。这样lambda知道它实现了哪个方法(知道它的签名,因此它知道所需参数的数量,它们的类型和类型或预期的返回值,如果有的话)。

我们也不说lambdas可以使用使用任何SAM(单一抽象方法 - 类似抽象类)类型,因为它只能用于SAM 接口(功能接口)。

So once again, lambdas can be used only with interfaces with one abstract method. This way lambda knows which method it implements (knows its signature so it knows number of required arguments, their type and type or expected returned value if any).
Also we don't say that lambdas can be used with any SAM (Single Abstract Method - like abstract classes) types, because it can be used only with SAM interfaces (functional interfaces).

这篇关于在Session中使用lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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