最近在公司写项目看到老板写代码时的一种新的写法,在这里作个记录。
- client里的readAllAndDelete方法
重点:里面的MailReader是一个接口,且接口中只有一个方法。
public interface MailReader {
boolean save(Mail mail);
}
- ->的使用(jdk1.8版本以后有的写法)
private void readEmail(Long emailid, String username, String password) throws Exception {
EmailClient client = clients.get(EmailHost.Yandex);
if (client == null)
throw new RuntimeException("can't found client for " + EmailHost.Yandex.getHost());
client.readAllAndDelete(username, password, "Inbox", (mail) -> {
mail.setEmailid(emailid);
try {
mailMapper.insert(mail);
} catch (Exception e) {
LoggerFactory.getLogger(this.getClass()).error(e.getMessage(), e);
return false;
}
return true;
});
// 更新邮箱updatetime
mailboxService.updateLastReceipt(emailid);
}
解析:里面client.readAllAndDelete(username, password, “Inbox”, (mail) -> { });相当于方法(为了便于理解就把代码简化了一下)
client.readAllAndDelete(username, password, "Inbox", new MailReader() {
@Override
public boolean save(Mail mail) {
// TODO Auto-generated method stub
mail.setEmailid(emailid);
return false;
}
});
- 代码的执行过程
从上到下依次执行……
-> { }相当于接口中save()方法的实现类。