java工具類該怎么寫(xiě)

java工具類該怎么寫(xiě)

  • 命名以復(fù)數(shù)(s)結(jié)尾,或者以Utils結(jié)尾

    Objects、Collections、IOUtilsFileUtils

  • 構(gòu)造器私有化

    構(gòu)造器私有化,這樣無(wú)法創(chuàng)建實(shí)例,也無(wú)法產(chǎn)生派生類

  • 方法使用 static 修飾

    因?yàn)闃?gòu)造器私有化了,那么對(duì)外提供的方法就屬于類級(jí)別

  • 異常需要拋出,不要 try-catch

    將異常交給調(diào)用者處理

  • 工具類不要打印日志

    工具類屬于公共的,所以不要有定制化日志

  • 不要暴露可變屬性

    工具類屬于公共類,所以不要暴露可變的屬性;如List集合等(可以返回不可變的集合,或者拷貝一個(gè)暴露給調(diào)用者,這樣調(diào)用者修改了集合中元素,不會(huì)影響到工具類中的集合元素)

示例(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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容