Hej. Mam klasę z wieloma polami i muszę sprawdzić wszystkie / część z nich czy nie są nullami. Wcześniej sprawdzałam ifami, ale teraz pomyślałam, żeby napisać coś takiego. Mam pytanie czy da się może robić to lepiej / otrzymać nazwę pola, które jest nullem (chciałabym rzucać wyjątkiem z odpowiednim komunikatem).
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.List;
class User {
private Long id;
private String name;
private Date created;
User(Long id, String name, Date created) {
this.id = id;
this.name = name;
this.created = created;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Date getCreated() {
return created;
}
}
class UserValidator {
public static boolean check(User user) {
List<Object> refs = Lists.newArrayList(
user.getId(),
user.getName()
);
return !refs.contains(null);
}
}
public class Main {
public static void main(String[] args) {
User user = new User(null, null, null);
System.out.println(UserValidator.check(user));
user = new User(1L, "aaaa", null);
System.out.println(UserValidator.check(user));
}
}