Import Static and Static Finals

In the past, I often used the "import static" construct in Java classes. I recently realized that instead

import static my.pack.A.MY_CONSTANT; 

you can use

 import my.pack.A; public class B { private static final MY_CONSTANT = A.MY_CONSTANT; } 

The most obvious benefits of this approach are:

  • You can use refactoring in Eclipse to easily separate all long constant expressions, such as ABCCONSTANT.ANOTHER_ONE.TOO_LONG from your code, without loading static imports (which were not so quickly mastered in Eclipse).
  • You can give any name to any expression that may be more meaningful in the current context.

For instance:

 private static final PAYMENT_TYPE = PaymentType.CASH; ... calculateSomething(amount, PAYMENT_TYPE); 

instead

 import static my.pack.PaymentType.CASH ... calculateSomething(amount, CASH); 

and it's also easier to refactor if the PaymentType defaults to CREDIT_CARD.

My question is: are there any drawbacks to this approach compared to static imports, or can it be used everywhere?

My only problem now is the resulting compiled .class file, which is probably different for the two approaches described. Thus, performance and memory usage could theoretically be affected.

+4
source share
2 answers

I believe that the only drawback is that you have more code where you assign one constant to another constant. Apart from this, there should be no difference. Performance and memory should not matter, most likely you will have more links to the same constant pool entries. Even if he created separate permanent entries in the pool, a lot will be required to change them.

The ability to give good names to constants can be a very good thing when it is not possible to rename the original records.

+5
source

This is mostly a matter of taste, but official docs are advised to use the static version sparingly, especially with a wildcard. The main disadvantage of static imports is that it pollutes your namespace by adding all the static members to it. In the example above, this should be about what you think is more readable for your code. Resist the urge to "import the package. *" Unless you really want all the static members of the package .

It should not affect your compiled code - it just provides reduced access to the same constant.

+3
source

All Articles