BAEL-5873: Check If All the Variables of a Class Are Null (#13285)

* model classes. unit tests. apache lang3 dependency.

* fix PR build
This commit is contained in:
pedrolopes 2023-01-12 23:28:36 -03:00 committed by GitHub
parent 3c12edb5f6
commit f6f63673a9
4 changed files with 108 additions and 0 deletions

View File

@ -13,4 +13,12 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,30 @@
package com.baeldung.nullchecking;
import java.util.Objects;
import java.util.stream.Stream;
public class Car {
Integer power;
Integer year;
public boolean allNull() {
if (power != null) {
return false;
}
if (year != null) {
return false;
}
return true;
}
public boolean allNullV2() {
return Stream.of(power, year)
.allMatch(Objects::isNull);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.nullchecking;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Objects;
public class NullChecker {
public static boolean allNull(Object target) {
return Arrays.stream(target.getClass()
.getDeclaredFields())
.peek(f -> f.setAccessible(true))
.map(f -> getFieldValue(f, target))
.allMatch(Objects::isNull);
}
private static Object getFieldValue(Field field, Object target) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.nullchecking;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class NullCheckUnitTest {
@Test
public void givenNullFields_whenCheckForNullsUsingIfs_thenReturnCorrectValue(){
Car car = new Car();
boolean result = car.allNull();
assertTrue(result);
}
@Test
public void givenNullFields_whenCheckForNullsUsingStreams_thenReturnCorrectValue(){
Car car = new Car();
boolean result = car.allNullV2();
assertTrue(result);
}
@Test
public void givenNullFields_whenCheckForNullsUsingApacheCommons_thenReturnCorrectValue(){
Car car = new Car();
boolean result = ObjectUtils.allNull(car.power, car.year);
assertTrue(result);
}
@Test
public void givenNullFields_whenCheckForNullsUsingReflection_thenReturnCorrectValue(){
Car car = new Car();
boolean result = NullChecker.allNull(car);
assertTrue(result);
}
}