更新時間:2022-07-13 10:50:48 來源:動力節點 瀏覽3269次
Java工具類怎么寫?動力節點小編來告訴大家。
1.命名以復數(s)結尾,或者以Utils結尾
如 Objects、Collections、IOUtils、FileUtils
2.構造器私有化
構造器私有化,這樣無法創建實例,也無法產生派生類
3.方法使用 static 修飾
因為構造器私有化了,那么對外提供的方法就屬于類級別
4.異常需要拋出,不要 try-catch
將異常交給調用者處理
5.工具類不要打印日志
工具類屬于公共的,所以不要有定制化日志
6.不要暴露可變屬性
工具類屬于公共類,所以不要暴露可變的屬性;如List集合等(可以返回不可變的集合,或者拷貝一個暴露給調用者,這樣調用者修改了集合中元素,不會影響到工具類中的集合元素)
示例(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;
}
}
以上就是關于“一文讀懂Java工具類怎么寫”的介紹,大家如果對此比較感興趣,想了解更多相關知識,不妨來關注一下動力節點的Java在線學習,里面的課程從入門到精通,細致全面,適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習