java面试题网

普通会员

483

帖子

9

回复

187

积分

楼主
发表于 2019-08-26 15:24:39 | 查看: 5018| 回复: 0

Guava Preconditions类

Guava Preconditions类

Preconditions提供静态方法来检查方法或构造函数,被调用是否给定适当的参数。它检查的先决条件。其方法失败抛出IllegalArgumentException。

类声明

以下是com.google.common.base.Preconditions类的声明:

@GwtCompatible
public final class Preconditions
   extends Object

类方法

Guava Preconditions类_www.wityx.com

Guava Preconditions类_www.wityx.com

继承的方法

这个类继承了以下类方法:

java.lang.Object

Preconditions 示例

使用所选择的编辑器,创建下面的java程序比如 C:/> Guava GuavaTester.java

import com.google.common.base.Preconditions;

public class GuavaTester {

   public static void main(String args[]){
      GuavaTester guavaTester = new GuavaTester();
      try {
         System.out.println(guavaTester.sqrt(-3.0));
      }catch(IllegalArgumentException e){
         System.out.println(e.getMessage());
      }
      try {
         System.out.println(guavaTester.sum(null,3));
      }catch(NullPointerException e){
         System.out.println(e.getMessage());
      }
      try {
         System.out.println(guavaTester.getValue(6));
      }catch(IndexOutOfBoundsException e){
         System.out.println(e.getMessage());
      }
   }

   public double sqrt(double input) throws IllegalArgumentException {
      Preconditions.checkArgument(input > 0.0,
         "Illegal Argument passed: Negative value %s.", input);
      return Math.sqrt(input);
   }	

   public int sum(Integer a, Integer b){
      a = Preconditions.checkNotNull(a,
         "Illegal Argument passed: First parameter is Null.");
      b = Preconditions.checkNotNull(b,
         "Illegal Argument passed: Second parameter is Null.");
      return a+b;
   }

   public int getValue(int input){
      int[] data = {1,2,3,4,5};
      Preconditions.checkElementIndex(input,data.length,
         "Illegal Argument passed: Invalid index.");
      return 0;
   }
}

验证结果

使用javac编译器编译如下类


C:Guava>javac GuavaTester.java

现在运行GuavaTester看到的结果


C:Guava>java GuavaTester

看到结果


Illegal Argument passed: Negative value -3.0.
Illegal Argument passed: First parameter is Null.
Illegal Argument passed: Invalid index. (6) must be less than size (5)


文章来自www.wityx.com,转载请注明出处!原文地址http://www.wityx.com/post/1246_1_1.html

上一篇:Guava Ordering类 下一篇:Guava Optional类
您需要登录后才可以回帖 登录 | 立即注册

java面试题网www.wuliaokankan.cnjava建站系统提供技术支持V2.1 网站地图 © 2016-2018