zoukankan      html  css  js  c++  java
  • Google Guava学习笔记——基础工具类Preconditions类的使用

      Preconditions类是一组静态方法用来验证我们代码的状态。Preconditons类很重要,它能保证我们的代码按照我们期望的执行,如果不是我们期望的,我们会立即得到反馈是哪里出来问题,现在我们使用Preconditions来保证我们代码的行为,并且对调试也非常方便。

      当然,你也可以自己写预处理的代码,就像下面一样:

    if (someObj == null) {
            throw new IllegalArgumentException(" someObj must not be null");
        }

      但使用Preconditions类来处理参数为空的情况,会更加清晰可读:

    Preconditions.checkNotNull(label, "Label can't not be null");

      下面的类演示了Preconditions类的使用:

      

    package com.guava.felix;
    
    import com.google.common.base.Preconditions;
    
    public class PreconditionsDemo {
    
        private String label;
    
        private int[] values = new int[5];
    
        private int currentIndex;
    
        public PreconditionsDemo(String label) {
        this.label = Preconditions.checkNotNull(label, "Label can't not be null");
        }
    
        public void updateCurrentIndexValue(int index, int valueToSet) {
        // check index valid first
        this.currentIndex = Preconditions.checkElementIndex(index, values.length, "Index out of bounds for values.");
        // validate valueToSet
        Preconditions.checkArgument(valueToSet <= 100, "Value can't be more than 100");
        values[this.currentIndex] = valueToSet;
        }
    
        public void doOperation() {
        Preconditions.checkState(validateObjectState(), "Can't perform operation.");
        }
    
        private boolean validateObjectState() {
        return this.label.equalsIgnoreCase("open") && values[this.currentIndex] == 10;
        }
    
        public static void main(String[] args) {
        PreconditionsDemo demo = new PreconditionsDemo("open");
    
        demo.updateCurrentIndexValue(4, 10);
    
        demo.doOperation();
    
        }
    
    }

     下面是例子中四个方法的总结:

      checkNotNull(T object, Object message): object对象不为空的话返回,否则抛出异常。

      checkElementIndex(int index, int size, Object message): index表示你要访问的数组,集合,字符串的位置,size表示的是长度,如果 index是有效的则返回,否则抛出异常;

      checkArgument(Boolean expression, Object message):这个方法根据传递进来的参数是否满足方法中的逻辑判断,如果符合,返回true,否则抛出异常。

      checkStatus(Boolean expression, Object message):这个方法没有参数,它判断一个对象的状态,期望返回true,否则抛出异常。

  • 相关阅读:
    ASP.NET MVC 3: Razor中的@:和语法
    telerik 值得学习 web mvc 桌面 控件大全
    Android 基于google Zxing实现对手机中的二维码进行扫描
    Android 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
    SQL聚集索引和非聚集索引的区别
    SQL Server的聚集索引和非聚集索引
    请教一个Jquery ligerui 框架的小问题
    学习如何用VS2010创建ocx控件
    nginx-rtmp-module--------------WIKI
    rtmp一些状态信息详解-as连接FMS服务器报错状态汇总~~
  • 原文地址:https://www.cnblogs.com/IcanFixIt/p/4511949.html
Copyright © 2011-2022 走看看