javastatic-import

static import for constants in same file


To reference a class constant in an annotation present on the same class, the reference must be prefixed with the class name:

package example;

@MyAnnotation(someAttribute = SomeClass.someConstant)
public class SomeClass {

    public static final someConstant = "...";

}

Since this can get quite bulky when using multiple constants / string concatenations, I might simply use the following import directive in the same file to eliminate the need for these prefixes:

package example;

import static example.SomeClass.*;

@MyAnnotation(someAttribute = someConstant + more + constants)
public class SomeClass {

    public static final someConstant = "...";
    public static final more = "...";
    public static final constants = "...";

}

Is there anything against this, or when could this lead to problems / ambiguities?

Java Language Specification Chapter 7.5.4 Static-Import-on-Demand Declarations: v8, v11, v17


Solution

  • Is there anything against this

    No, it's fine.

    when could this lead to problems / ambiguities?

    when you get really wild with defining symbols in the file whose names clash with the imports.

    For example:

    package example;
    
    import static example.SomeClass.*;
    
    class SomeClass {
      static int foo;
    
      void bar() {
        foo = 1;
    
        String foo = "";
        
        System.out.println(foo);  // Prints the local variable.
      }
    }
    

    but you should be giving yourself a stern talking to if you're writing code like this, so it's not really an issue.