Friday, 9 January 2015

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 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);
          
    }
   
}
How to import static variable in Eclipse


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.

Eclipse Shortcut for doing Static Import in JavaStatic Import in Eclipse

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);
          
    }
   
}

importing static variable in Java in Eclipse

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.

No comments:

Post a Comment