Do you know what is shortcut of doing static import in Eclipse? Well I didn't know before, but today I come to know that shortcut Ctrl+Shift+M (Source > Add Import) can not only be used to add missing imports but It can also help with static import in Java program. Suppose you are using lots of static variable from a utility class e.g. TimeUnit by referring them with class name, just like we refer static variable. In Eclipse IDE, you can select the whole reference variable and press Ctrl+Shift+M and it will automatically import that static element using static import in Java.
For example, if you have following code in your class, you can select TimeUnit.SECONDS and then use shortcut Ctrl+Shift+M to statically import SECONDS variable in your program, as shown in first and second screenshot.
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);
}
}
As shown here, Just highlight or select TimeUnit.SECONDS and type Ctrl+Shift+M or choose Menu option Add import to static import this static variable from java.util.TimeUnit class. By doing this three times in this program you can reduce above code into following code, also shown in fourth screenshot.
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);
}
}
By the way this feature is not that seamless e.g. it will not work if import to TimeUnit class is missing i.e. using Ctrl+Shift+M will have no effect if you have not imported java.util.concurrent.TimeUnit class already. Only after having this import in your code, you need to select member and press Ctrl+Shift+M to static import that field or method. Here also you cannot import all static members in one shot, you need to first select each of those element and then executing that shortcut for as many time as number of static members.
Dapatkan Freechip 25.000 Hanya Dengan Minimal Deposit 50.000 Saja loh!!!
BalasHapusPromo Ini Kita Adakan Untuk Memeriahkan Hari Kemerdekaan dan Juga untuk Menyambut Asian Games 2018 di Indonesia!!!
Promo Berlaku Tanggal tanggal 17 Agustus hingga 2 September 2018.
Ayo dicatat Tanggal Mulainya ya :)
*Syarat dan ketentuan berlaku*
Contact Kami :
BBM : D8B84EE1 / AGENS128
Line id : agens1288
WhatsApp : 0877-8922-1725