日常开发中整理的一些开箱即用的开源工具类,帮助减少冗余代码和项目中的重复轮子,主要提供商包括 Spring
, Apache common-lang3
, Lombok
, Guava
。
Assert
1 2 3 4 5 6 7 8 9 10 11 12 13
| if (input == null) { throw new IllegalArgument("given argument must not be null"); }
if (num != 1) { throw new IllegalArgument("given number is not 1"); }
Assert.notNull(input, "input is null");
Assert.isTrue(num == 1, "given number is not 1");
|
Safe equals
1 2 3 4 5
| !a.equals(b)
!Objects.equals(a, b)
|
StringUtils
1 2 3
| StringUtils.isEmpty(str); StringUtils.isBlank(str);
|
BooleanUtils
1 2 3 4 5 6 7 8 9 10 11
| Boolean b;
if (b == null || b == false) { }
if (BooleanUtils.isNotTrue) { }
|
defaultIfNull
1 2 3 4
| int expiration = ObjectUtils.defaultIfNull( Utils.getConfigValueAsInt(PROPERTY_EXPIRATION), DEFAULT_EXPIRATION);
|
Ignore Checked-Exception
Lombok @SneakyThrow
1 2 3 4 5 6 7 8
| public static void normalMethodWithThrowsIdentifier() throws IOException { throw new IOException(); }
@SneakyThrows public static void methodWithSneakyThrowsAnnotation() { throw new IOException(); }
|
Builder Pattern with Lombok
lombok Builder
Required arguments with a lombok @Builder
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import lombok.Builder; import lombok.ToString;
@Builder(builderMethodName = "hiddenBuilder") @ToString public class Person {
private String name; private String surname;
public static PersonBuilder builder(String name) { return hiddenBuilder().name(name); } }
|
Copied from SOF
guava
TODO
retry strategy
TODO