Should I use static import?

前端 未结 7 613
天命终不由人
天命终不由人 2020-12-16 12:45

How important it is to convert all my import to static import? Why are people still reluctant to use static import?

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 13:14

    I use static import when working with JUnit's assert (import static org.junit.Assert.*;) and also when I have an enum that is very tied to the class in question.

    For example:

    Enum file:

    public enum MyEnum {
       A, B, C;
    }
    

    Class file:

    import static MyEnum.*;
    
    public class MyClass {
      MyEnum e;
    
      public setE(MyEnum newE) {
        if ( newE == A ) {
           // some verification
        }
        e = newE;
      }
    }
    

    Note how I was able to do newE == A, instead of newE == MyEnum.A. Comes in handy if you do a lot of these throughout the code.

提交回复
热议问题