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 或其他异常处理机制来确保代码的正确性。

相关推荐
尊治14 小时前
变频器学习入门教程
学习·esim电工仿真·电工仿真软件·电工仿真·电工接线学习·esim电工制图
tyqtyq2215 小时前
旅行打包清单 App — HarmonyOS AI 应用开发技术博客
人工智能·学习·华为·生活·harmonyos
辞旧 lekkk16 小时前
【Redis初阶】常见数据类型
开发语言·数据库·c++·redis·学习·缓存·bootstrap
小弥儿17 小时前
GitHub今日热榜 | 2026-07-17:教育Agent与极低量化分庭抗礼
学习·开源·github
dtq042418 小时前
C语言-结构体详解
c语言·开发语言·学习
天选之子12319 小时前
DuckDB学习
jvm·学习
一只小菜鸡..19 小时前
Stanford CS144 学习笔记 (四):网络拥塞控制与 AIMD 算法
网络·笔记·学习
xuhaoyu_cpp_java20 小时前
SpringBoot学习(四)
java·经验分享·spring boot·笔记·学习
Eira-Z1 天前
git(持续学习中...)
git·学习
子非鱼94271 天前
07-Flutter 鸿蒙实战 07:故事集列表与缓存设计
学习·flutter·缓存·华为·harmonyos