Google Guava 学习记录《一》

Guava 在Google code 上地址:https://code.google.com/p/guava-libraries/

首先为什么要学习这个库,在实习的时候看大神的代码很简洁,很多地方将一些琐碎凌乱的代码轻松解决,所以抱着试试看的心态搞搞吧。

第一部分:basic utilities

  1. null 问题的处理

理解Optional<T> ,首先要理解为什么出现这个。在Java中null其实代表的意思在不同的content下是不同的,比如一个值可能是null或者是真的不存在。在Map.get时会return null 如果这个key的value没有找到或者也有可能是这个key不存在。"It's very easy to mix up the cases where a Map contains an entry for a key, with value null, and the case where the Map has no entry for a key"  这句话说的这个意思。而Optional出现就是为了让这个null清晰

上自己的测试代码,不是官方的。

package google.guava;


import com.google.common.base.*;

/**
 * Created by xiaoxin on 15-8-11.
 */
public class GuavaDemo {



    Optional<String> userName;


    public static void main(String []args){
        GuavaDemo gd = new GuavaDemo();

        String userNameFromReuqest = "userNameTest";

        gd.userName = Optional.of(userNameFromReuqest);

        gd.userName.isPresent();
        System.out.println(gd.userName.get());

        String nullUserName = null;

        gd.userName = Optional.fromNullable(nullUserName);
        System.out.println(gd.userName.isPresent());

    //利用Optional.fromNulllable(T)可以很好的处理一些可能为nulll的传值。
/* String userName = ..FromUnknowSourcce() gd.userName = Optional.fromNullable(userName); if (gd.userName.isPresent()){ handle username }else{ handle exception }*/ } }

    

 

non-null在Optional的理解就是 present,而null是absent,但不存在说我这个var里contain一个null。 即只有两种情况。

Optional的静态方法:

Optional.of(T) Make an Optional containing the given non-null value, or fail fast on null.
Optional.absent() Return an absent Optional of some type.
Optional.fromNullable(T) Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent

查询方法:

boolean isPresent() Returns true if this Optional contains a non-null instance. //如果Optional里是non-null就是返回true
T get() Returns the contained T instance, which must be present; otherwise, throws an IllegalStateException. //返回必须是non-null,否则抛出exception
T or(T) Returns the present value in this Optional, or if there is none, returns the specified default.//返回value如果是是non-null,如果是none,就返回特定的默认值,这里的默认值是你穿进去的参数
T orNull() Returns the present value in this Optional, or if there is none, returns null. The inverse operation of fromNullable.
Set<T> asSet() Returns an immutable singleton Set containing the instance in this Optional, if there is one, or otherwise an empty immutable set.

其实很多的处理null的情况都是String,所以有Strings的静态方法:  方法名就一目了然了~ 后面还有个Strings的专门章节

emptyToNull(String)
isNullOrEmpty(String)
nullToEmpty(String)

后记:有很多办法可以解决传参null问题,比如刚看到的@Nonnull,应该就是要求参数为null。后续慢慢补充这个Optional,在项目中用后应该理解的能更好点

原文地址:https://www.cnblogs.com/-Doraemon/p/4721379.html