2

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;
    }
}
4

2 回答 2

3

是的,这是可能的。

import static SecurityConstants.*

JLS 供参考。 7.5.4. 按需静态导入声明

按需静态导入声明允许根据需要导入命名类型的所有可访问静态成员。

StaticImportOnDemandDeclaration:
     import static TypeName . * ;

TypeName 必须是类类型、接口类型、枚举类型或注释类型的规范名称(第 6.7 节)。

于 2015-04-11T20:00:16.293 回答
1

just import the enum, then you call the enum instance direct. Also you if you make the enum instance name, the same as the text you want - no need to call getText().

You have to use a static import btw.

于 2015-04-11T19:53:32.667 回答