8000
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在写项目过程中,自己写了一些工具类,在此把自己的想法和做法记录一下。
A: 工具类统一放在 util 包内,工具类统一以 xxxUtils 命名,Utils 结尾。如 TimeUtils。
util
xxxUtils
Utils
TimeUtils
A: 以 TimeUtils 定义为例。
方式一,将构造方法私有化,再严格一点,在私有方法里面加个抛异常(防止通过反射调用,调用后会抛异常);final 修饰类说明不能被继承。
final
/** * @author techial */ public final class TimeUtils { private TimeUtils() { // throw new IllegalStateException("Utility class"); } }
方式二,巧用 abstract 关键字,抽象类不能被实例化,如果用反射去调用,会抛出异常。
abstract
你也可以继承这个抽象类,扩展这个工具类;不像方式一,不能继承扩展。
/** * @author techial */ public abstract class TimeUtils { }
A: public static 修饰方法,如果有传入的参数,尽量使用 @Nullable / @NonNull 注解,提醒调用者关于 null 情况检查。(加了注解 IDE 也会提醒)
public static
@Nullable
@NonNull
这两个注解是 Spring 里面的,IDEA 也有提供对应的注解。 @nullable 对象可能为 null @nonnull 对象不为 null
这两个注解是 Spring 里面的,IDEA 也有提供对应的注解。
@nullable 对象可能为 null
@nonnull 对象不为 null
/** * 返回今天零点 Instant */ public static Instant todayZeroTimeInstant() { return Instant.now().truncatedTo(ChronoUnit.DAYS); } import org.springframework.lang.Nullable; import org.springframework.lang.NonNull; public static boolean between(@Nullable Long start, @Nullable Long end, @Nullable Long target) { if (start == null || end == null || target == null) { return false; } return target > start && target < end; }
关于工具类,个人还是偏向于使用 abstract 关键字来定义类,思路来源于 Spring 的工具类。
final 加私有构造方法根据有点麻烦,毕竟你还要多手写一个私有构造方法。
其实在项目中还有一类用的比较多,也就是常量类,定义和工具类类似。
public abstract class ProfileConst { public static final String DEV = "dev"; public static final String PROD = "prod"; public static final String TEST = "test"; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Uh oh!
There was an error while loading. Please reload this page.
在写项目过程中,自己写了一些工具类,在此把自己的想法和做法记录一下。
Q: 关于工具类的命名 / 存放?
A: 工具类统一放在
util
包内,工具类统一以xxxUtils
命名,Utils
结尾。如TimeUtils
。Q: 关于工具类的定义?
A: 以
TimeUtils
定义为例。方式一,将构造方法私有化,再严格一点,在私有方法里面加个抛异常(防止通过反射调用,调用后会抛异常);
final
修饰类说明不能被继承。方式二,巧用
abstract
关键字,抽象类不能被实例化,如果用反射去调用,会抛出异常。你也可以继承这个抽象类,扩展这个工具类;不像方式一,不能继承扩展。
Q: 工具类方法怎么写?
A:
public static
修饰方法,如果有传入的参数,尽量使用@Nullable
/@NonNull
注解,提醒调用者关于 null 情况检查。(加了注解 IDE 也会提醒)other
关于工具类,个人还是偏向于使用
abstract
关键字来定义类,思路来源于 Spring 的工具类。final
加私有构造方法根据有点麻烦,毕竟你还要多手写一个私有构造方法。其实在项目中还有一类用的比较多,也就是常量类,定义和工具类类似。
The text was updated successfully, but these errors were encountered: