Java-如何定製自己的工具庫: mytools or myutil

來源:互聯網
上載者:User

掌握了包的知識後,就可以建立自己的工具庫來減少或消除重複的程式碼了。例如:給System.out.println()建立一個別名來減少輸入負擔。

package edu.foresthe.mytools;

public class P {

       public static void rint(String s) {

       System.out.print(s);

}

public static void rintln(String s) {

       System.out.println(s);

}

}

可以猜到,這個檔案的位置定是以某個CLASSPATH位置開始,然後接著是edu/foresthe/mytools的目錄下。編譯完之後,就可以用import語句在你的系統上使用P.class檔案了。

import edu.foresthe.mytools.*;

public class MyToolsTest {

       public static void main(String[] args) {

       P.rintln(“Available from now on!”);

       P.rintln(“” + 100); //Force it to be a String

       P.rintln(“” + 100L);

       P.rint(“” + 3.1415926);

}

}

額外話題:只要將所有對象放於String運算式之中,就可以輕易地將它們強行轉換為String的表達形式。上例中,以一個空String開始的運算式就是這種方法。但是,如果調用System.out.println(100),它無需將100轉型成String就可以工作(rintln()則不行)。通過某些額外的重載,也可以用P類達到同樣的目的。

恭喜你,從現在開始,只要你實現了某個新的有用工具,你就可以把它添加到自己的工具庫中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.