[英]Easiest way to check if property is null or empty in java
我有一個方法可以檢查Account的某些屬性(不是全部),並且如果這些屬性中的任何一個為null或為空,它都將返回true,那么我需要一種優雅的方法來執行此操作而不必編寫太多條件語句。
private boolean isInvalidSlateAccount(Account account) {
return (account.getAccesskeyid() == null || account.getAccesskeyid().trim().isEmpty()
|| account.getAccount() == null || account.getAccount().trim().isEmpty()
|| account.getAwsregion() == null || account.getAwsregion().trim().isEmpty()
|| account.getGatewayname() == null || account.getGatewayname().trim().isEmpty()
|| account.getGatewaytype() == null || account.getGatewaytype().trim().isEmpty()
|| account.getSecretaccesskey() == null || account.getSecretaccesskey().trim().isEmpty()
|| account.getTenant() == null || account.getTenant().trim().isEmpty() || account.getZone() == null || account
.getZone().trim().isEmpty());
}
我已經做到了
private boolean isInvalidSlateAccount(Account account) {
List<String> properties = Arrays.asList(
account.getAccesskeyid(),
account.getAccount(),
account.getAwsregion(),
account.getGatewayname(),
account.getGatewaytype(),
account.getSecretaccesskey(),
account.getTenant(),
account.getZone()
);
return properties.stream()
.anyMatch(s -> (s == null || s.trim().isEmpty()));
}
但這將檢查我不打算執行的Account對象的所有屬性的條件。 如何才能更優雅地做到這一點?
編寫一個方法isNullOrEmpty(String)
:
static boolean isNullOrEmpty(String s) {
return s == null || s.trim().isEmpty()
// Or return s == null || s.isBlank(); in Java 11+
}
所以你可以這樣寫:
return isNullOrEmpty(account.getAccesskeyid())
|| isNullOrEmpty(account.getAccount())
/* etc */;
我認為這樣做比做涉及構造流或列表的操作更可取,因為它很簡單 :它使用了非常基礎的語言功能,即使是新手程序員也很容易理解。
另外,它避免評估所有字段(例如,將String... ss
傳遞給isNullOrEmpty
,然后在數組上執行某些操作),因為它會短路,因為一旦找到第一個null或空值,它將立即停止串。
它還不需要創建任何對象(例如隱式數組或Arrays.asList(...)
的List
),這些對象僅僅是調用方法的偽像: trim()
確實可以創建對象,但這在評估病情的必要范圍內,這是“有用的”工作。
這似乎是標准Java Bean驗證框架JSR 380的經典用例。
它允許您將@NotNull
批注添加到Account類中的字段。 然后,您可以執行以下操作:
@NotNull
private String awsRegion;
Account account = new Account();
account.setAwsRegion(null)
Set<ConstraintViolation<Account>> violations = validator.validate(Account);
您將需要添加驗證API作為依賴項,以及驗證器實現,例如Hibernate參考實現:
<!-- Java eXtensions for Validation API -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- Java eXtensions for Unified Expression Language API -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<!-- Hibernate Validator as implementation of the JSR 349 Bean Validation Specification -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.0.Final</version>
</dependency>
這是一個讓您入門的鏈接:
https://www.baeldung.com/javax-validation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.