使用JavaMail API发邮件遇类型不兼容错误:需Void却得PasswordAuthentication
解决JavaMail API中“类型不兼容:找到'javax.mail.PasswordAuthentication',所需'java.lang.Void'”错误
你的代码存在语法错误,创建Authenticator匿名内部类时,错误提前闭合了new javax.mail.Authenticator()的括号,导致编译器把后续代码块当成Session.getDefaultInstance方法调用后的额外代码,而非Authenticator的子类实现,进而误解了getPasswordAuthentication方法的返回值类型。
修正后的代码如下:
session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Util.EMAIL, Util.PASSWORD); } }); return null; }
修正说明
- 移除
new javax.mail.Authenticator()后多余的右括号),让匿名内部类的大括号{紧跟在Authenticator()之后,确保代码块属于Authenticator子类的实现逻辑。 - 修正后
getPasswordAuthentication方法能正确重写父类的同名方法,返回类型与PasswordAuthentication匹配,不会再出现返回值类型不兼容的错误。
内容的提问来源于stack exchange,提问作者Khaled
相关产品推荐
相关产品推荐

