Saturday, May 16, 2015

Use import static in Java to extend the language

One confusing new feature is the ability to import a class as static.

   so if you have a class Foo and it has a method p() and q()

   then if you do
      import static Foo;

   suddenly you can get access to these methods without having to specify the host static class if it were not a static import, e.g. you can just go     p(something);

   it should not be used when inheritance is tricky, but rather to extend with some "primitives" like a language extenstion

  of course, it can be a useful way to get your enums and consts without having to always de-reference them off the class name, and that is it's best application.

One way I use static imports is to handle logging. My logger class has static methods for info, debug, and severe.  Once they are statically imported all I have to do is put

     info ("this did something");

in the code. And I get it nicely integrated with logging. It's also good for math or lambda functions!

No comments:

Post a Comment