Thursday, September 1, 2016

How to do static import in Eclipse - Java

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 7
*/
public class Test {  
   
    public static void main(String args[]){
       
        System.out.println(TimeUnit.SECONDS);
        System.out.println(TimeUnit.MINUTES);
        System.out.println(TimeUnit.DAYS);
         
    }
  
}

No comments:

Post a Comment