更新時間:2022-07-13 10:50:48 來源:動力節(jié)點(diǎn) 瀏覽3358次
Java工具類怎么寫?動力節(jié)點(diǎn)小編來告訴大家。
1.命名以復(fù)數(shù)(s)結(jié)尾,或者以Utils結(jié)尾
如 Objects、Collections、IOUtils、FileUtils
2.構(gòu)造器私有化
構(gòu)造器私有化,這樣無法創(chuàng)建實(shí)例,也無法產(chǎn)生派生類
3.方法使用 static 修飾
因?yàn)闃?gòu)造器私有化了,那么對外提供的方法就屬于類級別
4.異常需要拋出,不要 try-catch
將異常交給調(diào)用者處理
5.工具類不要打印日志
工具類屬于公共的,所以不要有定制化日志
6.不要暴露可變屬性
工具類屬于公共類,所以不要暴露可變的屬性;如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;
}
}
以上就是關(guān)于“一文讀懂Java工具類怎么寫”的介紹,大家如果對此比較感興趣,想了解更多相關(guān)知識,不妨來關(guān)注一下動力節(jié)點(diǎn)的Java在線學(xué)習(xí),里面的課程從入門到精通,細(xì)致全面,適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),希望對大家能夠有所幫助。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743