简体   繁体   中英

Java enum constructor error

I'm trying to create an enum class so that I can use each value in a for loop, getting each value one at a time.

This is my enum declaration:

public enum SpaceStyle {

    public SpaceStyle(spaceStyle1, spaceStyle2, spaceStyle3);
    private String key;

    SpaceStyle(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }
}

This is the for loop where I want to loop and use each method.

for (SpaceStyle key : SpaceStyle.values()) {
    Map<String, String> contentMap = createContentMap(conf, versionNumber, data);
    createAndPopulateSpace(conf, versionNumber, contentMap, key.toString());
}

// The final method where the key of the enum will be used.
public StudioResponse createSpace(ProductInstance conf, VersionNumber \
            versionNumber, String spaceName, String spaceKey, String key) {
    return conf.buildRequest("/createspace.action")
        .setArg("name", spaceName)
        .setArg("key", spaceKey)
        .setArg("permissionSetter.registeredCanView", "true")
        .setArg("permissionSetter.registeredCanEdit", "true")
        .setArg("themeKey", "com.atlassian.studio.confluence" + key)
        .execute("Creating space '" + spaceName + "'");
    }
}

That won't compile, because you can't have a public constructor in an enum.

This will compile:

public enum SpaceStyle {
    spaceStyle1("some-key"),
    spaceStyle2("some-other-key"),
    spaceStyle3("foo-bar");

    private String key;

    private SpaceStyle(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM