google 的guava 学习 基本工具类

Guava 是 Google 开发的一个 Java 核心库,它提供了一系列工具类,用于简化 Java 编程中的常见任务。以下是 PreconditionsVerify 两个工具类的使用示例:

Preconditions 类

Preconditions 类提供了一组静态方法,用于在代码中插入检查,确保方法的前提条件得到满足。如果条件不满足,它会抛出 IllegalArgumentException 或其他类型的异常。

java 复制代码
import com.google.common.base.Preconditions;

public class Example {
    public static void main(String[] args) {
        // 检查对象非空
        String str = "Hello, Guava!";
        Preconditions.checkNotNull(str, "The string should not be null.");

        // 检查条件
        Preconditions.checkArgument(str.length() > 0, "The string should not be empty.");
        
        // 检查状态
        boolean isTrue = true;
        Preconditions.checkState(isTrue, "This should be true.");
    }
}

Verify 类

Guava 提供了 Verify 工具类的第三方库是 truth。以下是 truth 库中的 Verify 类的使用示例:

首先,您需要添加 truth 库到您的项目中。如果您使用 Maven,可以在 pom.xml 文件中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>com.google.truth</groupId>
    <artifactId>truth</artifactId>
    <version>1.1.3</version>
    <scope>test</scope>
</dependency>

然后,您可以使用 Verify 类来验证对象状态:

java 复制代码
import com.google.common.truth.Truth;
import com.google.common.truth.Verify;

public class Example {
    public static void main(String[] args) {
        Verify.verify("Hello, Guava!").isNotNull();
        Verify.verify("Hello, Guava!").isNotEmpty();
    }
}

请注意,Verify 类主要用于测试中,而不是在生产代码中。它提供了一种简洁的方式来验证测试中的条件和状态。在生产代码中,您通常会使用 Preconditions 或其他异常处理机制来确保代码的正确性。

相关推荐
撩得Android一次心动1 小时前
Linux编程笔记4【个人用】
linux·笔记·学习
user-猴子1 小时前
让网页“活”过来 —— 用AI打造会自主学习的动态知识图谱
人工智能·学习·知识图谱
网络工程小王2 小时前
【HCIE-AI】10.pytorch模型迁移分析
人工智能·学习·华为·llama
魔城烟雨3 小时前
从零开始学习betaflight《3-硬件接口设计规范标准》
学习·设计规范
不言鹅喻6 小时前
HarmonyOS ArkTS 实战:实现一个单词背诵与英语学习应用
学习·华为·harmonyos
正经人_x6 小时前
学习日记42
学习
一只小菜鸡..6 小时前
南京大学 操作系统 (JYY) 学习笔记:导论与历史的轮回 (OS Introduction)
笔记·学习
小弥儿6 小时前
GitHub 今日热榜 | 2026-07-24:金融 K 线基础模型上榜
学习·金融·开源·github
520拼好饭被践踏7 小时前
JAVA+Agent学习day22
java·开发语言·后端·学习
懿路向前7 小时前
【HarmonyOS学习笔记】2026-07-24 | textProcessing 实体识别与踩坑实录
笔记·学习·边缘计算·harmonyos