I have enum which corresponds to encodings.I need to check that enum don’t have repeating number values for encodings.
public enum EncodingsEnum
{
ISO8859_1("ISO-8859-1",0), ISO8859_2("ISO-8859-2",1),
ISO8859_3("ISO-8859-3",2), ISO8859_4("ISO-8859-4",3),
ISO8859_5("ISO-8859-5",4), ISO8859_6("ISO-8859-6",5),
ISO8859_7("ISO-8859-7",6), ISO8859_8("ISO-8859-8",7),
ISO8859_9("ISO-8859-9",8), ISO8859_11("ISO-8859-11",9),
ISO8859_13("ISO-8859-13",10),ISO8859_15("ISO-8859-15",11),
UTF_8("UTF-8",11);
public static final int ENCODINGS_COUNT = EncodingsEnum.values().length;
private final String encodingName;
private final int encodingNumber;
EncodingsEnum(final String encodingName,int encodingNumber)
{
ReferenceChecker.checkReferenceNotNull(encodingName);
this.encodingName = encodingName;
this.encodingNumber = encodingNumber;
}
public static String getEncodingNameByNumber(int number)
{
for(EncodingsEnum encoding : EncodingsEnum.values())
{
if(encoding.encodingNumber == number)
{
return encoding.getEncodingName();
}
}
throw new RuntimeException("Encoding with this number isn't supported:" + number);
}
public static int getEncodingNumberByName(final String name)
{
for(EncodingsEnum encoding : EncodingsEnum.values())
{
if(encoding.encodingName.equals(name))
{
return encoding.getEncodingNumber();
}
}
throw new RuntimeException("Encoding with this name isn't supported:" + name);
}
public String getEncodingName()
{
return this.encodingName;
}
public int getEncodingNumber()
{
return this.encodingNumber;
}
}
There is a problem that I can create encoding with the same number as one of the existing encodings,so I need to check that enum contains element with this number and throw exception.But I dont know how to do that.Any idea?Thanks.
This shouldn’t be checked at runtime: it would be too late. Add a unit test that iterates through the enum values, and check that they all have a different number. And make sure to always execute the unit tests, and check that they pass, before generating a new version of your application/library.