在Eclipse中導(dǎo)入static元素
Eclipse中怎么快速導(dǎo)入Static變量、方法嗎?說實(shí)話,以前我也不知道。但是今天我知道了“Ctrl+Shift+M” (Source>Add Import)快捷鍵不僅可以增加缺失的導(dǎo)入,還可以用來在Java程序中導(dǎo)入靜態(tài)方法和變量。假設(shè)你正在從一個(gè)工具類,比如TimeUnit,通過類名使用很多靜態(tài)變量,也就是我們引用靜態(tài)變量。在Eclipse IDE中,你可以將引用變量完全選中并按下“Ctrl+Shift+M”快捷鍵,它會(huì)使用Java中的靜態(tài)導(dǎo)入來自動(dòng)導(dǎo)入靜態(tài)元素。
例如,如果你的類中有以下代碼,像***張和第二章截圖展示的那樣??梢赃x中TimeUnit.SECONDS,接著按下快捷鍵“Ctrl+Shift+M”來在代碼中靜態(tài)引入SECONDS變量。
- import java.util.concurrent.TimeUnit;
- /**
- * Java Program to show how you can static import some class variables.
- *
- * @author WINDOWS 8
- */
- public class Test {
- public static void main(String args[]){
- System.out.println(TimeUnit.SECONDS);
- System.out.println(TimeUnit.MINUTES);
- System.out.println(TimeUnit.DAYS);
- }
- }
像上面展示的那樣,僅需要標(biāo)記或選中TimeUnit.SECONDS,然后敲下“type Ctrl+Shift+M”快捷鍵或者選擇“Menu”選項(xiàng)中“Add import”來從java.util.TimeUnit類中引入靜態(tài)變量。在這段代碼中重復(fù)三次,可以將上面的代碼簡化為如下的代碼,如第四張截圖顯示的那樣:
- import static java.util.concurrent.TimeUnit.DAYS;
- import static java.util.concurrent.TimeUnit.MINUTES;
- import static java.util.concurrent.TimeUnit.SECONDS;
- import java.util.concurrent.TimeUnit;
- /**
- * Sample program to demonstrate Eclipse shortcut for doing static import.
- *
- * @author WINDOWS 8
- */
- public class Test {
- public static void main(String args[]){
- System.out.println(SECONDS);
- System.out.println(MINUTES);
- System.out.println(DAYS);
- }
- }
順便說一下,這個(gè)特性并不是沒有漏洞的。例如,如果你沒有提前導(dǎo)入java.util.concurrent.TimeUnit這個(gè)類,那么 TimeUnit class就會(huì)缺失。這樣的情況下, “Ctrl+Shift+M”快捷鍵是沒有效果的。只有在代碼中導(dǎo)入相應(yīng)類后,你需要選擇相應(yīng)成員,然后按下“ Ctrl+Shift+M”來引入靜態(tài)字段或方法。一次敲擊不能導(dǎo)入所有靜態(tài)成員,你需要首先選擇每一個(gè)這類元素,然后有多少個(gè)靜態(tài)成員,就按多少次快捷 鍵。
原文鏈接: javarevisited 翻譯: ImportNew.com - Calarence
譯文鏈接: http://www.importnew.com/14074.html