当前位置: 首页 > news >正文

Guava - Guava 基本工具 Preconditions、Optional

Guava

1、Guava 概述
  1. Guava 是 Google 开发的一款 Java 库,旨在弥补标准 JDK 的不足,提升开发效率和代码质量

  2. Guava 提供了一系列实用工具,覆盖了集合、缓存、字符串处理、并发编程等多个方面

2、Guava 引入
  • 在 pom.xml 文件中,引入相关依赖
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>32.1.3-jre</version>
</dependency>

Preconditions

1、基本介绍
  1. checkNotNull 方法:校验引用是否为 null。如果为 null,则抛出 NullPointerException

  2. checkArgument 方法:校验方法的参数是否满足条件。如果不满足,则抛出 IllegalArgumentException

  3. checkState 方法:校验对象的状态是否满足条件。如果不满足,则抛出 IllegalStateException

  4. checkPositionIndex 方法:检查插入位置的索引是否有效,用于在某个位置插入元素,有效范围为 0 ≤ index ≤ size。如果无效,则抛出 IndexOutOfBoundsException

  5. checkElementIndex 方法:检查某个元素的索引是否有效,用于访问已有元素,有效范围为 0 ≤ index < size。如果无效,则抛出 IndexOutOfBoundsException

  6. checkPositionIndexes 方法:检查一个范围是否有效,常用于子列表、子字符串等操作,有效条件为 0 ≤ start ≤ end ≤ size。如果无效,则抛出 IndexOutOfBoundsException

2、演示
  1. checkNotNull 方法
String input = null;try {Preconditions.checkNotNull(input, "input 不能为 null");
} catch (NullPointerException e) {System.out.println(e.getMessage());
}
  • 输出结果
input 不能为 null
  1. checkArgument 方法
int value = -1;try {Preconditions.checkArgument(value >= 0, "值必须 >= 0,实际是 %s", value);
} catch (IllegalArgumentException e) {System.out.println(e.getMessage());
}
  • 输出结果
值必须 >= 0,实际是 -1
  1. checkState 方法
boolean isReady = false;try {Preconditions.checkState(isReady, "未就绪");
} catch (IllegalStateException e) {System.out.println(e.getMessage());
}
  • 输出结果
未就绪
  1. checkPositionIndex 方法
List<String> list = Arrays.asList("A", "B", "C");
int index = -1;try {Preconditions.checkPositionIndex(index, list.size(), "非有效索引");
} catch (IndexOutOfBoundsException e) {System.out.println(e.getMessage());
}
  • 输出结果
非有效索引 (-1) must not be negative
  1. checkElementIndex 方法
List<String> list = Arrays.asList("A", "B", "C");
int index = -1;try {Preconditions.checkElementIndex(index, list.size(), "非有效索引");
} catch (IndexOutOfBoundsException e) {System.out.println(e.getMessage());
}
  • 输出结果
非有效索引 (-1) must not be negative
  1. checkPositionIndexes 方法
List<String> list = Arrays.asList("A", "B", "C");
int startIndex = -1;
int endIndex = 3;try {Preconditions.checkPositionIndexes(startIndex, endIndex, list.size());
} catch (IndexOutOfBoundsException e) {System.out.println(e.getMessage());
}
  • 输出结果
start index (-1) must not be negative
3、注意事项
  1. 测试用例中使用 try-catch 来包装 Preconditions 检查

  2. 但在实际应用中,建议让异常自然抛出,并在入口层统一处理


Optional

1、创建实例
  1. 使用 of 方法,值不能为 null,否则抛出异常 NullPointerException
Optional<String> present = Optional.of("Hello");
  1. 使用 absent 方法,明确表示值缺失
Optional<String> absent = Optional.absent();
  1. 使用 fromNullable 方法,值可能为 null
String str = getStr();Optional<String> fromNullable = Optional.fromNullable(str);
2、状态检查与值获取
(1)检查是否存在值
Optional<String> opt = Optional.fromNullable(null);if (opt.isPresent()) {System.out.println("value exist: " + opt.get());
} else {System.out.println("value not exist");
}
  • 当值为 null 时,输出结果
value not exist
Optional<String> opt = Optional.fromNullable("test");...
  • 当值不为 null 时,输出结果
value exist: test
(2)非安全获取值
Optional<String> opt = Optional.fromNullable(null);try {String value = opt.get();System.out.println("value: " + value);
} catch (IllegalStateException e) {System.out.println(e.getMessage());
}
  • 当值为 null 时,输出结果
Optional.get() cannot be called on an absent value
Optional<String> opt = Optional.fromNullable("test");...
  • 当值不为 null 时,输出结果
value: test
(3)安全获取值
Optional<String> opt = Optional.fromNullable(null);String safeValue = opt.or("safe value");System.out.println("value: " + safeValue);
  • 当值为 null 时,输出结果
value: safe value
Optional<String> opt = Optional.fromNullable("test");...
  • 当值不为 null 时,输出结果
value: test
(4)延迟获取值
Optional<String> opt = Optional.fromNullable(null);String lazyValue = opt.or(new Supplier<String>() {@Overridepublic String get() {return getLazyValue();}
});System.out.println("value: " + lazyValue);
private static String getLazyValue() {System.out.println("execute getLazyValue");return "lazy value";
}
  • 当值为 null 时,输出结果
execute getLazyValue
value: lazy value
Optional<String> opt = Optional.fromNullable("test");...
  • 当值不为 null 时,输出结果
value: test
(5)抛出指定异常
Optional<String> opt = Optional.fromNullable(null);try {String result = opt.or(new Supplier<String>() {@Overridepublic String get() {throw new IllegalArgumentException("value is required");}});System.out.println("result: " + result);
} catch (IllegalArgumentException e) {System.out.println(e.getMessage());
}
  • 当值为 null 时,输出结果
value is required
Optional<String> opt = Optional.fromNullable("test");...
  • 当值不为 null 时,输出结果
result: test
3、转换操作
(1)转换为大写
Optional<String> stringOpt = Optional.of("test content");Optional<String> upperOpt = stringOpt.transform(new Function<String, String>() {@Overridepublic String apply(String input) {return input.toUpperCase();}
});if (upperOpt.isPresent()) {System.out.println("value exist: " + upperOpt.get());
} else {System.out.println("value not exist");
}
  • 当值不为 null 时,输出结果
value exist: TEST CONTENT
Optional<String> stringOpt = Optional.fromNullable(null);...
  • 当值为 null 时,输出结果
value not exist
(2)转换为长度
Optional<String> stringOpt = Optional.fromNullable("test content");Optional<Integer> lengthOpt = stringOpt.transform(new Function<String, Integer>() {@Overridepublic Integer apply(String input) {return input.length();}
});if (lengthOpt.isPresent()) {System.out.println("value exist: " + lengthOpt.get());
} else {System.out.println("value not exist");
}
  • 当值不为 null 时,输出结果
value exist: 12
Optional<String> stringOpt = Optional.fromNullable(null);...
  • 当值为 null 时,输出结果
value not exist
(3)链式转换
Optional<Integer> doubleOpt = parseAndDouble("  123  ");if (doubleOpt.isPresent()) {System.out.println("value exist: " + doubleOpt.get());
} else {System.out.println("value not exist");
}
public static Optional<Integer> parseAndDouble(String numberStr) {return Optional.fromNullable(numberStr).transform(new Function<String, String>() {@Overridepublic String apply(String input) {return input.trim();}}).transform(new Function<String, Integer>() {@Overridepublic Integer apply(String input) {return Integer.parseInt(input);}}).transform(new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer input) {return input * 2;}});
}
  • 当值不为 null 时,输出结果
value exist: 246
Optional<Integer> doubleOpt = parseAndDouble(null);...
  • 当值为 null 时,输出结果
value not exist
http://www.dtcms.com/a/544487.html

相关文章:

  • 北京的电商平台网站有哪些内容做网站要多少钱 知乎
  • 北京网站建设 shwl营销单页网站
  • RISC-V开源处理器实战:从Verilog RTL设计到FPGA原型验证
  • Flutter兼容性问题:Namespace not specified
  • MoreFixes
  • 工业厂区人数进出显示屏让排班更科学
  • 分数阶微积分有限差分法求解
  • 软件设计师知识点总结:面向对象技术(面向对象基础+UML)
  • 【案例教程】从入门到精通-AI支持下的-ArcGIS数据处理、空间分析、可视化及多案例综合应用
  • 低压配电系统的AI进化(系统篇)
  • 注册网站代码装修平台网络推广公司
  • vue需要学习的点
  • Kotlin保留小数位的三种方法
  • GXDE OS 25.2.1 更新了!引入 dtk6,修复系统 bug 若干
  • Java 反序列化中的 boolean vs Boolean 陷阱:一个真实的 Bug 修复案例
  • Kotlin 类和对象
  • 内核里常用宏BUG_ON/WARN_ON/WARN_ONCE
  • 中断编程概念
  • EG1151 四开关升降压电源管理芯片技术解析
  • 腾讯云做网站教程专门做三国战纪的网站叫什么意思
  • 引航科技提供网站建设柳州企业网站建设公司
  • 钢铁行业数字化利器,TDengine 时序数据库荣获金恒科技“年度卓越供应商”
  • 分布式奇异值分解(SVD)详解
  • 线程局部存储(Thread-Local Storage, TLS)
  • 勇立潮头:优艾智合打造“一脑多态”工业具身智能新范式
  • 怕故障?怕扩展难?分布式可视化控制:给足场景安全感
  • HTML5 Audio(音频)
  • 返利网一类的网站怎么做网站设计与网页制作模板
  • CMD 的 echo 不支持像 Linux 那样用引号输出多行内容
  • 网站建设的优缺点域名换了网站需要备案么