validating - Guava Assertions

本文介绍Guava库中提供的断言工具类Verify,该工具类提供了一组始终可用的断言方法,无需开启Java原生断言。通过示例演示了如何使用Verify进行数值校验、空值检查等操作,并展示了不同情况下的错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Because turning on native Java assertions is a bother, the Guava team added a Verify class with replacement assertions always enabled.

The team recommends importing the Verify methods staticlly:

// validating/GuavaAssertions.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Assertions that are always enabled.

import static com.google.common.base.Verify.*;

import com.google.common.base.*;

public class GuavaAssertions {
  public static void main(String[] args) {
    verify(2 + 2 == 4);
    try {
      verify(1 + 2 == 4);
    } catch (VerifyException e) {
      System.out.println(e);
    }
    try {
      verify(1 + 2 == 4, "Bad math");
    } catch (VerifyException e) {
      System.out.println(e.getMessage());
    }
    try {
      verify(1 + 2 == 4, "Bad math: %s", "not 4");
    } catch (VerifyException e) {
      System.out.println(e.getMessage());
    }
    String s = "";
    s = verifyNotNull(s);
    s = null;
    try {
      verifyNotNull(s);
    } catch (VerifyException e) {
      System.out.println(e.getMessage());
    }
    try {
      verifyNotNull(s, "Shouldn't be null: %s", "arg s");
    } catch (VerifyException e) {
      System.out.println(e.getMessage());
    }
  }
}
/* Output:
com.google.common.base.VerifyException
Bad math
Bad math: not 4
expected a non-null reference
Shouldn't be null: arg s
*/

run GuavaAssertions

$ ./gradlew validating:GuavaAssertions

verifyNotNull()'s built-in error message is recommended.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/validating/GuavaAssertions.java 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值