3751_Creator
3751_Creator

Reputation: 664

Java give a possible list for a parameter

I want to create a parameter with multiple possibilities. To be more precise, in the method, I would like to have different levels of warning like 0,1,2 and 3. When you type it gives you have only these 4 possibilities.

Eg: setFoobar(1, "Yo");

Upvotes: 0

Views: 70

Answers (2)

qqilihq
qqilihq

Reputation: 11474

Consider using an enum for that:

public enum Severity {
    DEBUG, INFO, WARN, ERROR
}

[edit] Imagine, you have some method for logging a message with different urgency. The enum signifies that. In your method, you could then do something like:

switch (severity) {
    case DEBUG:
        // ignore
        break;
    case INFO:
        System.out.println(message);
        break;
    case WARN:
    case ERROR:
        System.err.println(message);
        break;
}

... or just do some comparisons:

if (severity == Severity.WARN || severity == Severity.ERROR) {
    System.err.println(message);
}

Beside that, an enum is much like a normal class, which means that you can add state (as in instance variables) and methods. For example, you could move the logic given above directly into the enum like so:

public enum Severity {

    DEBUG("Some low-level logging output"), 
    INFO("Informational output"), 
    WARN("A warning"), 
    ERROR("A serious error");

    private String description;

    private Severity(String description) {
        this.description = description;
    }

    public void output(String message) {
        switch (this) {
            case DEBUG:
                // ignore
                break;
            case INFO:
                System.out.println(message);
                break;
            case WARN:
            case ERROR:
                System.err.println(message);
                break;
        }
    }

    public String getDescription() {
        return description;
    }

}

Upvotes: 3

GreySwordz
GreySwordz

Reputation: 356

Java enums can provide this type of functionality.

Upvotes: 0

Related Questions