Guava-Preconditions & Strings

2022-03-12  本文已影响0人  63f4fe6cfa47

Preconditions

用来做断言的,可以使代码变得优雅,不需要通过if去判断,并且还能抛出自定义内容的异常
checkNotNull

    public void test1(){
        checkNotNullErrorMsg(null);
    }

    private void checkNotNullErrorMsg(final List<String> list){
        Preconditions.checkNotNull(list,"结果为空!期望结果为 %s",2);
    }
image.png
checkElementIndex
    public void test2(){
        //创建元素为a b的一个集合
        List<String> list = ImmutableList.of("a", "b");
        checkElementIndex(list);
    }

    private void checkElementIndex(final List<String> list){
        Preconditions.checkElementIndex(2,list.size(),"bad result:");
    }
image.png

Strings

emptyToNull&nullToEnpty

    public void test1(){
        assertThat(Strings.emptyToNull(""),nullValue());
        assertThat(Strings.emptyToNull("a"),equalTo("a"));
        assertThat(Strings.nullToEmpty(null),equalTo(""));
        assertThat(Strings.nullToEmpty("a"),equalTo("a"));
    }

commonPrefix&commonSuffix

    public void test2(){
        assertThat(Strings.commonPrefix("hello","hi"),equalTo("h"));
        assertThat(Strings.commonPrefix("hello","no"),equalTo(""));
        assertThat(Strings.commonSuffix("hello","no"),equalTo("o"));
        assertThat(Strings.commonSuffix("hello","hi"),equalTo(""));
    }

isNullOrEmpty

    public void test3(){
        assertThat(Strings.isNullOrEmpty(null),equalTo(true));
        assertThat(Strings.isNullOrEmpty(""),equalTo(true));
    }

padStart&padEnd

    public void test4(){
        assertThat(Strings.padStart("hello",6,'X'),equalTo("Xhello"));
        assertThat(Strings.padEnd("hello",6,'X'),equalTo("helloX"));
    }
上一篇 下一篇

猜你喜欢

热点阅读