今天想起来几本书上都有建议使用static import,所以去查了下:
从java doc里面可以看到,这个东西设计的初衷是为了方便调用而已。
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
翻译如果照字面做都不容易达意,只能直接解释上下文了,
以前(before1.5)使用常量,只能俩个方式:
- 用ConstantClass.constantField
- 定义在接口里面,然后让使用的类去implement它,这个就可以直接使用constantField
第二个方式似乎用起来稍微好看点,但是它会造成类多出来许多成员【可以说是name空间污染】,特别是这个影响对它的子类也存在,这个滥用的代码技巧会导致类的成员泛滥,很多java书里面都称为对继承的滥用。jdk早期代码里面这样的东西很多。
jdk1.5就加入了这样的代码糖(code sugar).【通过javap查看,static import跟ConstantClass.constantField没任何的区别,能看到都是被直接编译过去的,“ 3: ldc #22; //String c123”】
doc对于static import的使用也提出了建议,也不要滥用,一般控制在一两个类里面。
So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes.
个人不赞同这个用法,不过在unit test里面,会这样的使用org.junit.Assert的static方法,原因也很简单,unit test的上下文环境里面,Assertion操作本来就是非常普通的。