javaimportstatic-import

Enums shorthand calls - static imports


I am getting a little bit confused with import statements for enums. Consider following snippet:

UsernamePasswordAuthenticationFilter getUsernamePasswordAuthenticationFilter() {

    UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter =
            new UsernamePasswordAuthenticationFilter();
    usernamePasswordAuthenticationFilter.setAllowSessionCreation(false);
    usernamePasswordAuthenticationFilter.setUsernameParameter(SecurityConstants.CREDENTIALS_USERNAME.getText());
    usernamePasswordAuthenticationFilter.setPasswordParameter(SecurityConstants.CREDENTIALS_PASSWORD.getText());

This particular notation is too long:

SecurityConstants.CREDENTIALS_PASSWORD.getText()

to justify the usage of enum alltogether in this case. Is it possible to refer to enum like CREDENTIALS_PASSWORD.getText()?

I don't know why I have that feeling that it is possible, maybe JUnit assert statements static imports reflect in my brain as you can do short way assertEquals() with static imports.

Is there a way to do simillar with the enums?

Enum class itself:

public enum SecurityConstants {
    CREDENTIALS_PROCESSING_URL("app/authenticate"),
    CREDENTIALS_USERNAME("username"),
    CREDENTIALS_PASSWORD("password");

    private String text;

    SecurityConstants(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

Solution

  • Yes, it's possible.

    import static SecurityConstants.*
    

    JLS for the reference. 7.5.4. Static-Import-on-Demand Declarations

    A static-import-on-demand declaration allows all accessible static members of a named type to be imported as needed.

    StaticImportOnDemandDeclaration:
         import static TypeName . * ;
    

    The TypeName must be the canonical name (§6.7) of a class type, interface type, enum type, or annotation type.