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

相关推荐
进击的小头23 分钟前
第16篇:Buck-Boost 升降压电路:核心原理、参数计算与典型应用场景全讲解
经验分享·学习·数学建模
霸道流氓气质36 分钟前
Java 工程师 AI 智能体学习路线 · 阶段 1:AI / LLM 基础认知 详解
java·人工智能·学习
hunter1990101 小时前
Higress学习
学习
zzzll11112 小时前
Typora插件开发指南:打造专属IDE式写作环境
ide·学习·计算机·大模型·llm·知识
qq_263_tohua2 小时前
第110期 FCN 语义分割学习
深度学习·学习
chh5632 小时前
C++--vector
开发语言·c++·学习·算法
霸道流氓气质2 小时前
Java 工程师 AI 智能体学习路线 · 阶段 7:框架与生态 详解
java·人工智能·学习
星幻元宇VR17 小时前
公共安全实训展厅设备【人防知识学习系统】
科技·学习·安全
心中有国也有家20 小时前
AtomGit Flutter 鸿蒙客户端:情绪日记的时间线实现
学习·flutter·华为·harmonyos
百里香酚兰21 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习