2

I have a number of Enums each of which contain the names of attributes to be tested. The problem I have is how to select the relevant enum for the object. How can I define just a Enum variable which use throughout my code which can be set through an initalise method.

EDIT:

Sorry for the delayed reponse. I had to step away from the desk

It very well be bad design. I have a few enums as follows:

public enum AccountGrpEnum {
    Account("Account"),
    AccountType("AccountType"),
    AcctIDSource("AcctIDSource");

    private static Set<String> grpNames = new HashSet<String>(3) {{       
        for(AccountGrpEnum e : AccountGrpEnum.values()) {          
            add(e.toString());       
        }     
    }}; 

    public static boolean contains(String name) {       
        return grpNames.contains(name);     
    } 

    private String name;

    private AccountGrpEnum(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }

}

Another Enum:

public enum BlockManValEnum {

    avgPx("avgPx"),
    quantity("quantity"),
    securityIDSource("securityIDSource"),
    securityID("securityID"),
    blockStatus("blockStatus"),
    side("side");

    private static Set<String> names = new HashSet<String>(9) {{       
        for(BlockManValEnum e : BlockManValEnum.values()) {          
            add(e.toString());       
        }     
    }}; 

    public static boolean contains(String name) {       
        return names.contains(name);     
    } 

    private String name;

    private BlockManValEnum(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }

}

Within my code I am checking the fields of an incoming object to see they are contained within the Enum. As follows:

if (BlockManValEnum.contains(fields[i].getName()))

however I would like it to be along the lines of

if (variableEnum.contains(fields[i].getName()))

Where variableEnum can be set at runtime.

Hope this is clearer guys

700 Software
  • 85,281
  • 83
  • 234
  • 341
Will
  • 8,246
  • 16
  • 60
  • 92
  • 1
    Could you provide some more specific details? – S.L. Barth is on codidact.com Sep 01 '11 at 14:12
  • 1
    Your question is not very clear. **a)** it seems that Number should be lower case, unless you are talking about a `Number` object which does not make sense. **b)** It would be much easier to answer you if you would post the code in question, or example code to accomplish the same task. Can you do this? (sooner the better, downvotes on questions can come in kinda fast, you may want to [delete] your question and post it again more detailed.) – 700 Software Sep 01 '11 at 14:12
  • Honestly? I do not understand what do you mean at all :) But for me it looks as a really ugly design of tests. – omnomnom Sep 01 '11 at 14:13
  • Do you want dynamic enums? If that is the case, it's not possible. [Old Question](http://stackoverflow.com/questions/478403/can-i-add-and-remove-elements-of-enumeration-at-runtime-in-java) – TJ- Sep 01 '11 at 14:14
  • Hi guys added some more detail to the question. Hope it helps – Will Sep 01 '11 at 14:40

3 Answers3

2

Building on previous answers.

enum Color {
    RED(1),
    GREEN(2),
    BLUE(3);

    int attrib;

    Color(int attribValue) {
        attrib = attribValue;
    }

    public Color getColorForAttrib(int attribValue) {
        for(Color c : Color.values()) {
            if(c.attrib == attribValue) {
                return c;
            }
        }
        throw new IllegalArgumentException("No color could be found for attrib of value " + attribValue);
    }
}

...


class SomeClass {
    Color c;
    public void SomeClass(Color c) {
        this.c = c;
    }
 }

...

class SomeClassUser {
    public static void main(String[] args) {
        Color c = Color.getColorForAttrib(Integer.valueOf(args[i]));
        new SomeClass(c);
    }
}

Remember that simplistically, enums are just a class, so you can add any methods you want to them. Whether or not it's a good idea depends on circumstance

Ray Tayek
  • 9,841
  • 8
  • 50
  • 90
extorn
  • 611
  • 1
  • 5
  • 11
1

Use Enum.valueOf:

Enum<?> variableEnum = AccountGrpEnum.class;
if(Enum.valueOf(variableEnum.getClass(), field[i].getName()) != null) {
   doSomething();
}
Daniel
  • 10,115
  • 3
  • 44
  • 62
  • but some of the Enums have common attributes. With how will it know the correct Enum to use? – Will Sep 01 '11 at 14:55
  • See the above edit. You can use whichever enum type you want. The `if` statement does exactly the same as your `if (BlockManValEnum.contains(fields[i].getName()))` and `if (variableEnum.contains(fields[i].getName()))`. – Daniel Sep 27 '11 at 05:20
0

Since enums are classes and thus can implement interfaces, you could create an interface which holds your contains() method and then implement that method on your enums, then use a generic method which takes a class token of a specific enum type implementing that interface (and which could be set at runtime) to test. Something like this:

CanBeTestedForContains:

public interface CanBeTestedForContains {
  boolean contains(String name);
}

ColorEnum:

import java.util.HashSet;
import java.util.Set;

public enum ColorEnum implements CanBeTestedForContains {
  R("red"),
  B("blue");

  private static Set<String> names = new HashSet<String>(3) {
    {
      for (final ColorEnum e : ColorEnum.values()) {
        add(e.name);
      }
    }
  };

  private String name;

  private ColorEnum(final String name) {
    this.name = name;
  }

  @Override
  public boolean contains(final String name) {
    return names.contains(name);
  }
}

SuitEnum:

import java.util.HashSet;
import java.util.Set;

public enum SuitEnum implements CanBeTestedForContains {
  D("diamonds"),
  H("hearts"),
  C("clubs"),
  S("spades");

  private static Set<String> names = new HashSet<String>(3) {
    {
      for (final SuitEnum e : SuitEnum.values()) {
        add(e.name);
      }
    }
  };

  private String name;

  private SuitEnum(final String name) {
    this.name = name;
  }

  @Override
  public boolean contains(final String name) {
    return names.contains(name);
      }
}

ContainsSelectorTest:

public class ContainsSelectorTest {
  private static <E extends Enum<E> & CanBeTestedForContains> boolean contains(final Class<E> enumClass, final String name) {
    return enumClass.getEnumConstants()[0].contains(name);
  }

  public static void main(final String[] args) {
    if (contains(ColorEnum.class, "red")) {
      System.out.printf("%s contains %s\n", ColorEnum.class, "red");
    }

    if (contains(SuitEnum.class, "hearts")) {
      System.out.printf("%s contains %s\n", SuitEnum.class, "hearts");
    }

    if (contains(SuitEnum.class, "red")) {
      System.out.println("This shouldn't happen.");
    } else {
      System.out.printf("%s DOES NOT contain %s\n", SuitEnum.class, "red");
    }
  }
}

Output:

class ColorEnum contains red

class SuitEnum contains hearts class

class SuitEnum DOES NOT contain red

Community
  • 1
  • 1
Tom Tresansky
  • 19,364
  • 17
  • 93
  • 129