java工具類該怎么寫
-
命名以復(fù)數(shù)(s)結(jié)尾,或者以Utils結(jié)尾
如
Objects
阵子、Collections
示辈、IOUtils
、FileUtils
-
構(gòu)造器私有化
構(gòu)造器私有化掌桩,這樣無法創(chuàng)建實例边锁,也無法產(chǎn)生派生類
-
方法使用 static 修飾
因為構(gòu)造器私有化了,那么對外提供的方法就屬于類級別
-
異常需要拋出波岛,不要 try-catch
將異常交給調(diào)用者處理
-
工具類不要打印日志
工具類屬于公共的茅坛,所以不要有定制化日志
-
不要暴露可變屬性
工具類屬于公共類,所以不要暴露可變的屬性则拷;如List集合等(可以返回不可變的集合贡蓖,或者拷貝一個暴露給調(diào)用者,這樣調(diào)用者修改了集合中元素煌茬,不會影響到工具類中的集合元素)
示例(JDK中Arrays摘錄典型部分):
public class Arrays {
/**
* The minimum array length below which a parallel sorting
* algorithm will not further partition the sorting task. Using
* smaller sizes typically results in memory contention across
* tasks that makes parallel speedups unlikely.
*/
private static final int MIN_ARRAY_SORT_GRAN = 1 << 13;
// Suppresses default constructor, ensuring non-instantiability.
private Arrays() {}
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
public static int[] copyOfRange(int[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
int[] copy = new int[newLength];
System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
return copy;
}
}