Using a class for constants is unusual. In most cases, an interface is used. Access to it will ActionConstants.VALIDFIRSTLASTNAME :
public interface ActionConstants { static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+"; static final String VALIDPHONENUMBER = "\\d{10}"; ... } -Za-z0-9 \\ s.] +"; public interface ActionConstants { static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+"; static final String VALIDPHONENUMBER = "\\d{10}"; ... } { public interface ActionConstants { static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+"; static final String VALIDPHONENUMBER = "\\d{10}"; ... }
Starting with Java 5, you can also use the transfer. An enumeration can have members or advanced functionality.
The second example uses a simple element (here with the general approach, if you have different types of permanent, or you can also use the element String ):
public enum ActionConstants { FIRSTLASTNAME("[A-Za-z0-9.\\s]+"), PHONENUMBER("\\d{10}"); private final Object value; private ActionConstants(Object value) { this.value= value; } @SuppressWarnings("unchecked") public <T> T getValue() { return (T)value; } } String value = ActionConstants.FIRSTLASTNAME.getValue(); z0-9. \\ s] +"), public enum ActionConstants { FIRSTLASTNAME("[A-Za-z0-9.\\s]+"), PHONENUMBER("\\d{10}"); private final Object value; private ActionConstants(Object value) { this.value= value; } @SuppressWarnings("unchecked") public <T> T getValue() { return (T)value; } } String value = ActionConstants.FIRSTLASTNAME.getValue(); { public enum ActionConstants { FIRSTLASTNAME("[A-Za-z0-9.\\s]+"), PHONENUMBER("\\d{10}"); private final Object value; private ActionConstants(Object value) { this.value= value; } @SuppressWarnings("unchecked") public <T> T getValue() { return (T)value; } } String value = ActionConstants.FIRSTLASTNAME.getValue();
The last example uses extended functionality when all the constants are of the same type. You can use it as ActionConstants.PHONENUMBER.isValid("0800123456") :
public enum ActionConstants { FIRSTLASTNAME("[A-Za-z0-9.\\s]+"), PHONENUMBER("\\d{10}"); private final Pattern pattern; private ActionConstants(String pattern) { this.pattern = Pattern.compile(pattern); } public void isValid(String value) { return pattern.matcher(value).matches(); } } z0-9. \\ s] +"), public enum ActionConstants { FIRSTLASTNAME("[A-Za-z0-9.\\s]+"), PHONENUMBER("\\d{10}"); private final Pattern pattern; private ActionConstants(String pattern) { this.pattern = Pattern.compile(pattern); } public void isValid(String value) { return pattern.matcher(value).matches(); } } ; public enum ActionConstants { FIRSTLASTNAME("[A-Za-z0-9.\\s]+"), PHONENUMBER("\\d{10}"); private final Pattern pattern; private ActionConstants(String pattern) { this.pattern = Pattern.compile(pattern); } public void isValid(String value) { return pattern.matcher(value).matches(); } }
Both versions allow static import.
source share