标签:
1 int i = 4; 2 int j = 5; 3 Preconditions.checkArgument(i>j,"i should bigger than j, but i is %s and j is %s",i,j);
Exception in thread "main" java.lang.IllegalArgumentException: i should bigger than j, but i is 4 and j is 5 at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145) at google.guava.GuavaDemo.main(GuavaDemo.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
先放上最常用的checkArgument,可以看到当没有满足表达式时,输出的错误消息可以自己定义,而且非常清晰。
以下是对3个参数的解释:
其他的应该用的很少,在项目中ack发现只有用到过checkArgument了。。就不做解释了
checkArgument(boolean) | Checks that the boolean is true. Use for validating arguments to methods. | IllegalArgumentException |
checkNotNull(T) | Checks that the value is not null. Returns the value directly, so you can use checkNotNull(value) inline. | NullPointerException |
checkState(boolean) | Checks some state of the object, not dependent on the method arguments. For example, an Iteratormight use this to check that next has been called before any call to remove. | IllegalStateException |
checkElementIndex(int index, int size) | Checks that index is a valid element index into a list, string, or array with the specified size. An element index may range from 0 inclusive to size exclusive. You don‘t pass the list, string, or array directly; you just pass its size. Returns index. |
IndexOutOfBoundsException |
checkPositionIndex(int index, int size) | Checks that index is a valid position index into a list, string, or array with the specified size. A position index may range from 0 inclusive to size inclusive. You don‘t pass the list, string, or array directly; you just pass its size. Returns index. |
IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) |
Google Guava 学习记录《二》 Precondition
标签:
原文地址:http://www.cnblogs.com/-Doraemon/p/4721475.html