1

G'day, errata ... My plan was as shown below. This update is to clarify and apologise for a late night question. The compile error was due to a problem elsewhere in the file.

Clarification: a simple Java enum, like this:

public enum ServiceSource
{
    NONE,
    URL,
    FILE;

}

Want to checking like, isURL():

 public boolean isURL(){

    return (URL == this);
}

This works (and compiles) ... There's no question -- Correctly answered by: dasblinkenlight and Elliott Frisch. Thank you very much for your time.

see also:

Community
  • 1
  • 1
will
  • 4,799
  • 8
  • 54
  • 90

4 Answers4

5

Since this is an instance method, you need to check that this is equal to URL, like this:

public boolean isURL(){
    return (URL == this);
}

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

If you want to have methods that are polymorphic - i.e. exhibit different behaviour for different instances (values) of your enum class, my preference is to override a common method:

public enum ServiceSource {

    NONE("no_value"),
    URL("url"){

        @Override
        public boolean isURL() {
            return true;
        }

    },
    FILE("file");

    private final String val;

    private ServiceSource(String val) {
        this.val = val;
    }

    public boolean isURL() {
        return false;
    }
}

But for methods that check whether this is specific enum value then adding an isXXX method for each constant seems very wasteful. Really, the very reason to use an enum, is so that you can write

if(thing == ServiceSource.URL) 

Elsewhere in your code.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

If I understand your question, the correct method in your enum is to use this like so,

public enum ServiceSource
{
  NONE(   "no_value"  ),
  URL(    "url"       ),
  FILE(   "file"      );
  ServiceSource(String v) {
    text =v;
  }
  private String text;
  public boolean isURL() {
    return this == URL;
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can make a method on your Enum to check the value of itself like this:

  public boolean isURL(){
    return (URL == this);
  }

But it's hard to see the value in this approach since every Object has a built in equals() method that accomplishes the same thing.

if (serviceSource.equals(ServiceSource.URL)) { ... }

This would be a more common and obvious way to check the assigned value of an Enum variable (or any variable for that matter). Taking the first approach would require you to have a new isX() method on your Enum; every time you add an Enum constant, you would probably want a new method to accompany it.

Cameron
  • 1,868
  • 3
  • 21
  • 38