BAEL-5844: Convert Anonymous Class into Lambda in Java (#13088)

This commit is contained in:
Azhwani 2022-12-12 08:53:16 +01:00 committed by GitHub
parent 29d97308f6
commit a288f8db7e
5 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package com.baeldung.anonymousclass;
public class EmailSenderService implements SenderService {
@Override
public String callSender(Sender sender) {
return sender.send("Email Notification");
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.anonymousclass;
public interface Sender {
String send(final String message);
}

View File

@ -0,0 +1,7 @@
package com.baeldung.anonymousclass;
public interface SenderService {
String callSender(Sender sender);
}

View File

@ -0,0 +1,10 @@
package com.baeldung.anonymousclass;
public class SmsSenderService implements SenderService {
@Override
public String callSender(Sender sender) {
return sender.send("SMS Notification");
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.anonymousclass;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class AnonymousClassToLambdaIntegrationTest {
@Test
public void whenPassingAnonymousClass_thenSuccess() {
final SenderService emailSenderService = new EmailSenderService();
final String emailNotif = emailSenderService.callSender(new Sender() {
@Override
public String send(String message) {
return message;
}
});
assertEquals(emailNotif, "Email Notification");
}
@Test
public void whenPassingLambdaExpression_thenSuccess() {
final SenderService smsSenderService = new SmsSenderService();
final String smsNotif = smsSenderService.callSender((String message) -> {
return message;
});
assertEquals(smsNotif, "SMS Notification");
}
}