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

相关推荐
pop_xiaoli7 分钟前
【iOS】YYModel源码学习
学习·ios·objective-c·cocoa
嵌入式-老费35 分钟前
esp32开发与应用(利用loopback学习can)
学习
xianrenli382 小时前
DS5900作业之“氛围(Vibe)”背后的伦理
学习·ai编程·msai
iuu_star2 小时前
Python大模型智能学习平台——设计与实现(AI教学系统)
大数据·人工智能·python·学习
三品吉他手会点灯3 小时前
嵌入式机器学习 - 学习笔记1.2.3 - 机器学习软件框架
人工智能·笔记·嵌入式硬件·学习·机器学习
凌晨7点3 小时前
DAB拓扑学习01:系统整理-基于南航杨敏的论文(持续更新中......)
学习
YangYang9YangYan3 小时前
2026数字经济专业毕业发展指南
物联网·学习
武陵悭臾4 小时前
Python应用开发学习:如何让随机数按一定比列出现
python·学习·random·概率·随机数
渣渣灰飞4 小时前
MySQL 系统学习 第六阶段:Redis + 缓存 + 高并发设计 第八章:Redis 高级应用
学习·mysql·缓存
Kobebryant-Manba5 小时前
学习Bert
学习·自然语言处理·bert