Preconditions作为Guava中的异常的前置检查,提供了一系列方法。用于API实现者检查API参数的合法性。
其中前置检查主要为
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
public static <T> T checkNotNull(T reference)
检查是否为空
public static int checkElementIndex(int index, int size)
检查元素的索引是否超出0~size
public static int checkPositionIndex(int index, int size)
判断索引错误或size小于0,返回format
public static void checkPositionIndexes(int start, int end, int size) {
if (start < 0 || end < start || end > size) {
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
private static String badElementIndex(int index, int size, String desc)
private static String badPositionIndexes(int start, int end, int size)
其中 Preconditions 中实现了format 构造字符串
static String format(String template, @Nullable Object... args) {
template = String.valueOf(template);
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i;
int placeholderStart;
for(i = 0; i < args.length; templateStart = placeholderStart + 2) {
placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
}
builder.append(template.substring(templateStart));
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while(i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
}