首页 > 其他分享 >常用工具类

常用工具类

时间:2022-11-27 00:55:06浏览次数:40  
标签:assertTrue assertEquals void Assertions Test null 常用工具

Apache-Commons-*

字符串

判断字符串是否为空白字符串

以前判断字符串是否为空:

if ((name == null) || (name.isEmpty())){}

使用 apache-common-lang3StringUtils

void testIsBlank() {
   // true
   Assertions.assertTrue(StringUtils.isBlank(" "));

   // true
   Assertions.assertTrue(StringUtils.isBlank(""));

   // true
   Assertions.assertTrue(StringUtils.isBlank(null));

   // false
   Assertions.assertFalse(StringUtils.isBlank("foo"));

   // true
   Assertions.assertTrue(StringUtils.isAnyBlank(null, " "));

   // false
   Assertions.assertFalse(StringUtils.isAnyBlank("foo", " bar "));
}
左边填充字符串

有时候我们需要生成流水号,例如4位数的流水号,从1开始其余用字符'0'填充,就可以使用 leftPad 方法,示例如下:

@Test
void testLeftPad() {
   // 0001
   Assertions.assertEquals("0001", StringUtils.leftPad("1", 4, '0'));
}
右边填充字符串
@Test
void testRightPad() {
   // 1000
   Assertions.assertEquals("1000", StringUtils.rightPad("1", 4, '0'));
}
分割字符串
// ["a","b","c"]
Assertions.assertEquals(Arrays.toString(new String[]{"a", "b", "c"}), Arrays.toString(StringUtils.split("a,b,c", ",")));
字符串比较
// true
Assertions.assertTrue(StringUtils.equals(null, null));

// false
Assertions.assertFalse(StringUtils.equals("null", null));
字符串已指定子字符串开头
@Test
void testStartWith() {
   // true
   Assertions.assertTrue(StringUtils.startsWith("hello,world", "hello"));

   // false
   Assertions.assertFalse(StringUtils.startsWith("你好,世界", "世界"));
}

数值工具类

转换为 int 类型

将字符串转换为 int 类型,toInt(String str) 在转换失败的时候会返回默认值 0,如果需要指定默认值那么可以使用 toInt(final String str, final int defaultValue)

@Test
void testToInt() {
   // 0
   Assertions.assertEquals(0, NumberUtils.toInt("abc"));

   // 0
   Assertions.assertEquals(0, NumberUtils.toInt("01c"));

   // 0
   Assertions.assertEquals(0, NumberUtils.toInt("1a3"));

   // 1
   Assertions.assertEquals(1, NumberUtils.toInt("foo", 1));

   // 11
   Assertions.assertEquals(11, NumberUtils.toInt("11"));

   // 11
   Assertions.assertEquals(11, NumberUtils.toInt("011", 3));
}

数组

判断数组是否为空
@Test
void testIsEmpty() {
   // true
   Assertions.assertTrue(ArrayUtils.isEmpty(new Object[]{}));

   // false
   Assertions.assertFalse(ArrayUtils.isEmpty(new String[]{"foo"}));
}

日期

增加指定天数

除了增加指定的天数,common-lang3 还提供了:

  1. addHours:增加指定小时
  2. addMonths:增加指定月数
  3. 等...
@Test
void testAddDay() {
   Date now = new Date();
   Date tomorrow = DateUtils.addDays(now, 1);

   Assertions.assertEquals(1, Duration.ofMillis(tomorrow.getTime() - now.getTime()).toDays());
   Assertions.assertEquals(Duration.ofDays(1).toMillis(), Duration.ofMillis(tomorrow.getTime() - now.getTime()).toMillis());
}
格式化日期
tring pattern = "yyyy-MM-dd HH:mm:ss";
Date d1 = DateUtils.parseDate("2022-10-22 00:00:00", pattern);

Assertions.assertEquals("2022-10-22 00:00:00", DateFormatUtils.format(d1, pattern));
判断是否为同一天
String parsePattern = "yyyy-MM-dd HH:mm:ss";
Date d1 = DateUtils.parseDate("2022-10-22 00:00:00", parsePattern);
Date d2 = DateUtils.parseDate("2022-10-22 23:59:59", parsePattern);
// true
Assertions.assertTrue(DateUtils.isSameDay(d1, d2));

d1 = DateUtils.parseDate("2022-10-23 00:00:00", parsePattern);
d2 = DateUtils.parseDate("2022-10-22 00:00:00", parsePattern);
// false
Assertions.assertFalse(DateUtils.isSameDay(d1, d2));

枚举

@Test
void testGetEnum() {
   Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> Season.valueOf("Spring"));

   // 默认返回null,不抛出异常
   Assertions.assertNull(EnumUtils.getEnum(Season.class, "spring"));
   // 指定默认值
   Assertions.assertEquals(Season.SPRING, EnumUtils.getEnumIgnoreCase(Season.class, "spring"));
   // 忽略大小写匹配
   Assertions.assertEquals(Season.SPRING, EnumUtils.getEnum(Season.class, "spring", Season.SPRING));
}

enum Season {
   SPRING,
}

Guava

分割字符串

在了解 Guava 提供的字符串分割器之前,我们先来看看 Java 提供的字符串分隔有什么缺点,如下所示,输出的结果为:

",a,,b,".split(",")
  1. "", "a", "", "b", ""
  2. null, "a", null, "b", null
  3. "a", null, "b"
  4. "a", "b"
  5. 以上都不对

正确输出结果是 [, a, , b],答案是选项5:“以上都不对”。Splitter 不仅实现了字符串分隔,还提供了对应的修饰符,即对拆分结果进行处理,例如:

String str = "foo, bar ,,,baz";
// ["foo","bar","baz"]
Splitter.on(",")
      .trimResults()
      .omitEmptyStrings()
      .splitToList(str);

// [上下上下左, 左, 右右]
str = "baba上下上下左a左b右右";
res = Splitter.on(CharMatcher.inRange('a', 'b'))
      .trimResults()
      .omitEmptyStrings()
      .splitToList(str);
// [上下上下左, 左, 右右]      
log.info("{}", res);
拆分器工厂
方法 描述 示例
Splitter.on(char) 按单个字符拆分 Splitter.on(',');
Splitter.on(CharMatcher) 按字符匹配器拆分 Splitter.on(CharMatcher.inRange('a', 'b'))
Splitter.on(String) 按字符串拆分 Splitter.on(", ")
Splitter.on(Pattern)或onPattern(String) 按正则表达式拆分 Splitter.on("\r?\n ")
Splitter.fixedLength(int) 按固定长度拆分;最后一段可能比给定长度短,但不会为空。 Splitter.fixedLength(3)
拆分器修饰符
方法 描述
omitEmptyStrings() 从结果中自动忽略空白字符串
trimResults() 移除结果字符串的首位空白字符
trimResults(CharMatcher) 给定匹配器,移除结果字符串的首位匹配字符
limit(int) 限制拆分出的字符串数量

不可变集合

public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
        "red",
        "orange",
        "yellow",
        "green",
        "blue",
        "purple");

class Foo {
    Set<Bar> bars;
    Foo(Set<Bar> bars) {
        this.bars = ImmutableSet.copyOf(bars); // defensive copy!
    }
}

不可变对象有很多的优点:

  1. 当对象被不可信的库调用时,不可变形式是安全的;
  2. 不可变对象被多个线程调用时,不存在竞态条件问题
  3. 不可变集合不需要考虑变化,因此可以节省时间和空间。所有不可变的集合都比它们的可变形式有更好的内存利用率(分析和测试细节);
  4. 不可变对象因为有固定不变,可以作为常量来安全使用。
使用不可变集合

不可变集合可以用如下多种方式创建:

  1. copyOfImmutableList.copyOf
  2. ofImmutableList.of("a","b","c")
  3. Builder 工具,例如:
public static final ImmutableSet<Color> GOOGLE_COLORS =
        ImmutableSet.<Color>builder()
            .addAll(WEBSAFE_COLORS)
            .add(new Color(0, 191, 255))
            .build();

连接字符串

@Test
void testJoin() {
   // foo,bar
   Assertions.assertEquals("foo,bar", Joiner.on(',').join(ImmutableList.of("foo", "bar")));

   // foo
   Assertions.assertEquals("foo", Joiner.on(',').skipNulls().join("foo", null));

   // foo,empty
   Assertions.assertEquals("foo,empty", Joiner.on(',').useForNull("empty").join("foo", null));


   // 抛出空指针异常
   Assertions.assertThrowsExactly(NullPointerException.class, () -> Joiner.on(',').join("foo", null));
}

警告:joiner实例总是不可变的。用来定义joiner目标语义的配置方法总会返回一个新的joiner实例。这使得joiner实例都是线程安全的,你可以将其定义为static final常量。

Strings

null 转换为空字符串:

Assertions.assertEquals("", Strings.nullToEmpty(null));

将空字符串转换为 null

Assertions.assertEquals(null, Strings.emptyToNull(""));
Assertions.assertEquals(null, Strings.emptyToNull(null));

CharMatcher

String noControl = CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); //移除control字符
String theDigits = CharMatcher.DIGIT.retainFrom(string); //只保留数字字符
String spaced = CharMatcher.WHITESPACE.trimAndCollapseFrom(string, ' ');
//去除两端的空格,并把中间的连续空格替换成单个空格
String noDigits = CharMatcher.JAVA_DIGIT.replaceFrom(string, "*"); //用*号替换所有数字
String lowerAndDigit = CharMatcher.JAVA_DIGIT.or(CharMatcher.JAVA_LOWER_CASE).retainFrom(string);
// 只保留数字和小写字母

Spring

判断集合是否为空

@Test
void testIsEmpty() {
   Assertions.assertTrue(CollectionUtils.isEmpty((List<?>) null));
   Assertions.assertTrue(CollectionUtils.isEmpty((Set<?>) null));
   Assertions.assertTrue(CollectionUtils.isEmpty((Map<?, ?>) null));

   Assertions.assertTrue(CollectionUtils.isEmpty(Collections.emptyList()));
   Assertions.assertTrue(CollectionUtils.isEmpty(Collections.emptySet()));
   Assertions.assertTrue(CollectionUtils.isEmpty(Collections.emptyMap()));

   Assertions.assertTrue(CollectionUtils.isEmpty(List.of()));
   Assertions.assertTrue(CollectionUtils.isEmpty(Set.of()));
   Assertions.assertTrue(CollectionUtils.isEmpty(Map.of()));

   List<Object> list = new LinkedList<>();
   list.add(new Object());
   Assertions.assertFalse(CollectionUtils.isEmpty(list));
   Assertions.assertFalse(CollectionUtils.isEmpty(List.of("foo")));

   Map<String, String> map = new HashMap<>();
   map.put("foo", "bar");
   Assertions.assertFalse(CollectionUtils.isEmpty(map));
   Assertions.assertFalse(CollectionUtils.isEmpty(Map.of("foo", "bar")));
}

获取集合的第一个元素

@Test
void testFirstElement() {
   Assertions.assertNull(CollectionUtils.firstElement((Set<?>) null));
   Assertions.assertNull(CollectionUtils.firstElement((List<?>) null));

   List<String> list = new ArrayList<>();
   list.add(null);
   // null
   Assertions.assertNull(CollectionUtils.firstElement(list));

   list = new ArrayList<>();
   list.add("foo");
   // foo
   Assertions.assertEquals("foo", CollectionUtils.firstElement(list));

   list = List.of("foo", "bar");
   // foo
   Assertions.assertEquals("foo", CollectionUtils.firstElement(list));


   Set<String> set = new TreeSet<>();
   set.add("b");
   set.add("a");
   // a
   Assertions.assertEquals("a", CollectionUtils.firstElement(set));

   // b
   set = new TreeSet<>(Comparator.reverseOrder());
   set.add("b");
   set.add("a");
   Assertions.assertEquals("b", CollectionUtils.firstElement(set));
}

获取集合的最后一个元素

@Test
void testLastElement() {
   Assertions.assertNull(CollectionUtils.lastElement((Set<?>) null));
   Assertions.assertNull(CollectionUtils.lastElement((List<?>) null));

   List<String> list = new ArrayList<>();
   list.add(null);
   Assertions.assertNull(CollectionUtils.lastElement(list));

   list = new ArrayList<>();
   list.add("foo");
   list.add("bar");
   // bar
   Assertions.assertEquals("bar", CollectionUtils.lastElement(list));

   list = List.of("foo", "bar");
   Assertions.assertEquals("bar", CollectionUtils.lastElement(list));

   Set<String> set = new TreeSet<>();
   set.add("b");
   set.add("a");
   // b
   Assertions.assertEquals("b", CollectionUtils.lastElement(set));

   set = new TreeSet<>(Comparator.reverseOrder());
   set.add("b");
   set.add("a");
   // a
   Assertions.assertEquals("a", CollectionUtils.lastElement(set));
}

对象属性拷贝

添加一个测试对象:

class User {
   private String name;
   private String email;
   
   // 忽略getXxx和setXxx方法
@Test
void testCopyProperties() {
   User user =  new User();
         user.setName("foo");
         user.setEmail("bar");

   User target = new User();
    
   // 拷贝属性
   BeanUtils.copyProperties(user, target, "email");

   Assertions.assertEquals("foo", target.getName());
   Assertions.assertNull(target.getEmail());
}

命名的 ThreadLocal

@Test
void testNamedThreadLocal() {
   NamedThreadLocal<String> threadLocal = new NamedThreadLocal<>("task");
   Assertions.assertEquals("task", threadLocal.toString());
}

判断对象是否相等

@Test
void testNullSafeEquals() {
   Assertions.assertTrue(ObjectUtils.nullSafeEquals(null, null));
   Assertions.assertTrue(ObjectUtils.nullSafeEquals("a", "a"));
   Assertions.assertTrue(ObjectUtils.nullSafeEquals(Optional.of("a"), Optional.of("a")));
}

判断对象是否为空

@Test
void testIsEmpty() {
   Assertions.assertTrue(ObjectUtils.isEmpty((Object) null));
   Assertions.assertTrue(ObjectUtils.isEmpty(Optional.empty()));
   Assertions.assertTrue(ObjectUtils.isEmpty(""));
   Assertions.assertTrue(ObjectUtils.isEmpty(new String[]{}));
   Assertions.assertTrue(ObjectUtils.isEmpty(Collections.emptyList()));
   Assertions.assertTrue(ObjectUtils.isEmpty(Collections.emptyMap()));
}

资源工具类

有时候我们需要加载 classpath 目录下的资源,例如:

File file = new File(ResourceUtilsTests.class.getClassLoader().getResource("log4j2.xml").toURI());
Assertions.assertEquals("log4j2.xml", file.getName());

使用 SpringResourceUtils 只需要这么写:

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "log4j2.xml");
Assertions.assertEquals("log4j2.xml", file.getName());

计时器

@Test
void testStopWatch() throws InterruptedException {
   // 创建一个计时器(秒表)
   StopWatch stopWatch = new StopWatch();
   // 开始计时
   stopWatch.start();
   Thread.sleep(Duration.ofSeconds(1).toMillis());
   // 停止计时
   stopWatch.stop();
   // 获取总耗时(毫秒)
   // 1005ms.
   log.info("{}ms.", stopWatch.getTotalTimeMillis());
   // 1s.
   log.info("{}s.", Duration.ofMillis(stopWatch.getTotalTimeMillis()).toSeconds());
}

UriComponentsBuilder

有时候我们需要在服务端手动发送请求,在请求 url 我们使用字符串拼接的方式,Spring 提供了UriComponentsBuilder 能让我们更加语意化来构建一个请求url,而且还会自动对url进行编码:

@Test
void testFromUriString() {
   String uri = UriComponentsBuilder
         .fromUriString("/coffee/{foo}/{id}/like")
         .build("aa", "bb")
         .toString();
   Assertions.assertEquals("/coffee/aa/bb/like", uri);

   uri = UriComponentsBuilder
         .fromUriString("http://localhost:8080/coffe/{id}")
         .encode()
         .build(1).toString();
   Assertions.assertEquals("http://localhost:8080/coffe/1", uri);

   uri = UriComponentsBuilder
         .fromUriString("http://localhost:8080/coffee?name={name}")
         .build(" ").toString();
   Assertions.assertEquals("http://localhost:8080/coffee?name=%20",uri);
}

hutool

校验

@Test
void testIsCitizenId() {
   // 校验是否为身份证
   Assertions.assertTrue(Validator.isCitizenId("110101199003074477"));

   // 15位身份证号码验证
   Assertions.assertTrue(Validator.isCitizenId("410001910101123"));

   // 10位身份证号码验证
   Assertions.assertTrue(Validator.isCitizenId("U193683453"));
}

@Test
void testIsMobile() {
   // 校验是否为手机号
   Assertions.assertTrue(Validator.isMobile("13900221432"));
   Assertions.assertTrue(Validator.isMobile("015100221432"));
   Assertions.assertTrue(Validator.isMobile("+8618600221432"));
}

@Test
void testIsPlateNumber() {
   // 校验是否为车牌号
   Assertions.assertTrue(Validator.isPlateNumber("粤BA03205"));
   Assertions.assertTrue(Validator.isPlateNumber("闽20401领"));
}

emoji

@Test
void testToUnicode() {
   String unicode = EmojiUtil.toUnicode(":smile:");
   Assertions.assertEquals("

标签:assertTrue,assertEquals,void,Assertions,Test,null,常用工具
From: https://www.cnblogs.com/doug-shaw/p/java-utility-classes.html

相关文章

  • 转:web开发常用工具
    测试网站加载时间​​​http://www.iwebtool.com​​​http://tools.pingdom.com/fpt/使用Pingdomtools的用户可测试他们的网站加载时间并找出......
  • java常用工具方法
    double类型后补0privateStringroundByScale(doublev,intscale){if(scale<0){thrownewIllegalArgumentException("Thescal......
  • 【JS】1012- 52个JavaScript常用工具函数整理
    1、isStatic:检测数据是不是除了symbol外的原始数据。functionisStatic(value){return(typeofvalue==='string'||typeofvalue==='number'|......
  • JavaScript常用工具函数
    检测数据是不是除了symbol外的原始数据functionisStatic(value){return(typeofvalue==='string'||typeofvalue==='number'||typeofvalue......
  • 在线常用工具
    在线白板:https://excalidraw.com/ 在线MD5加密、解密:https://www.cmd5.com/ https://pmd5.com/?action=getpwd# 在线天气预报:http://www.weather.com.cn/weathe......
  • 【MySQL高级】MySql中常用工具及Mysql 日志
    1.MySql中常用工具1.1mysql该mysql不是指mysql服务,而是指mysql的客户端工具。语法:mysql[options][database]1.1.1连接选项参数:-u,--user=name指......
  • Linux常用工具和命令总结
    一.Linux常用命令1.Linux常用命令列表命令作用常用参数参数作用ls列出指定目录的列表,包括文件和子目录。默认是当前目录-l以列表方式查看-a显示隐含文件和目录-h以便于阅读的......
  • php 常用工具函数
    返回时间戳差值部分,年、月、日functionget_date_diff($startstamp,$endstamp,$return='m'){$y=date('Y',$endstamp)-date('Y',$startstamp);$m=d......
  • MYSQL-->客户端常用工具指令
    mysql这个mysql指的是mysql的客户端管理工具语法mysql选项数据库选项内容-u指定用户名-p指定密码-h指定ip地址-P指定端口-e执行SQL语句并退出-e选项可......
  • MySQL——常用工具和日志
    一、MySql中常用工具1.1、mysql该mysql不是指mysql服务,而是指mysql的客户端工具。语法:mysql[options][database]连接选项参数: -u,--user=name指定用户名 -p,......