Guava - Guava 基本工具 Preconditions、Optional
Guava
1、Guava 概述
-
Guava 是 Google 开发的一款 Java 库,旨在弥补标准 JDK 的不足,提升开发效率和代码质量
-
Guava 提供了一系列实用工具,覆盖了集合、缓存、字符串处理、并发编程等多个方面
2、Guava 引入
- 在 pom.xml 文件中,引入相关依赖
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>32.1.3-jre</version>
</dependency>
Preconditions
1、基本介绍
-
checkNotNull 方法:校验引用是否为 null。如果为 null,则抛出 NullPointerException
-
checkArgument 方法:校验方法的参数是否满足条件。如果不满足,则抛出 IllegalArgumentException
-
checkState 方法:校验对象的状态是否满足条件。如果不满足,则抛出 IllegalStateException
-
checkPositionIndex 方法:检查插入位置的索引是否有效,用于在某个位置插入元素,有效范围为
0 ≤ index ≤ size。如果无效,则抛出 IndexOutOfBoundsException -
checkElementIndex 方法:检查某个元素的索引是否有效,用于访问已有元素,有效范围为
0 ≤ index < size。如果无效,则抛出 IndexOutOfBoundsException -
checkPositionIndexes 方法:检查一个范围是否有效,常用于子列表、子字符串等操作,有效条件为
0 ≤ start ≤ end ≤ size。如果无效,则抛出 IndexOutOfBoundsException
2、演示
- checkNotNull 方法
String input = null;try {Preconditions.checkNotNull(input, "input 不能为 null");
} catch (NullPointerException e) {System.out.println(e.getMessage());
}
- 输出结果
input 不能为 null
- checkArgument 方法
int value = -1;try {Preconditions.checkArgument(value >= 0, "值必须 >= 0,实际是 %s", value);
} catch (IllegalArgumentException e) {System.out.println(e.getMessage());
}
- 输出结果
值必须 >= 0,实际是 -1
- checkState 方法
boolean isReady = false;try {Preconditions.checkState(isReady, "未就绪");
} catch (IllegalStateException e) {System.out.println(e.getMessage());
}
- 输出结果
未就绪
- 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
- 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
- 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、注意事项
-
测试用例中使用 try-catch 来包装 Preconditions 检查
-
但在实际应用中,建议让异常自然抛出,并在入口层统一处理
Optional
1、创建实例
- 使用 of 方法,值不能为 null,否则抛出异常 NullPointerException
Optional<String> present = Optional.of("Hello");
- 使用 absent 方法,明确表示值缺失
Optional<String> absent = Optional.absent();
- 使用 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
