public enum Role{
ADMIN("SMITH","KEVIN"),
STUDENT("JACK", "JILL", "MARRY", "MALA"),
GURDIAN("BOB");
}
How can I define constructor for this enum in JAVA?
Can I initiate as follows?
Role(List<String> userlist){}
public enum Role{
ADMIN("SMITH","KEVIN"),
STUDENT("JACK", "JILL", "MARRY", "MALA"),
GURDIAN("BOB");
}
How can I define constructor for this enum in JAVA?
Can I initiate as follows?
Role(List<String> userlist){}
The most suitable constructor I can think of is with a String varargs, as follows:
Role(String... names) {
// TODO
}
A constructor taking List<String> will not match the signature and will not compile on its own.
You can always overload the constructors though.
You definitely go with the varargs style constructor
private final List<String> values;
Role(String... values) {
this.values = Arrays.asList(values);
}
public List<String> getValues() {
return values;
}
And then when you need the particular role based on the provided names go for the find as
public static Role find(String name) {
for (Role role: Role.values()) {
if (rol.getValues().contains(name)) {
return rol;
}
}
return null;
}
You can use use variable arguments varargs in constructor like:
public enum Role {
ADMIN("SMITH","KEVIN"),
STUDENT("JACK", "JILL", "MARRY", "MALA"),
GURDIAN("BOB");
private Role(String...name) {
this.values = name;
}
}
public enum Role{
ADMIN("SMITH","KEVIN"),
STUDENT("JACK", "JILL", "MARRY", "MALA"),
GURDIAN("BOB");
private String[] values;
Role(String ... values) {
this.values = values;
}
}
There is declaration (in enum), storage in field, and usage.
As these are singletons, defined in the enum class, the form of the declaration is only important with respect to elegance.
public enum Role{
ADMIN(user("SMITH", "KEVIN")),
STUDENT(user("JACK", "JILL"), user("MARRY", "MALA")),
GURDIAN(user("BOB"));
// Local factory methods
// User or Principal
private User user(String firstname, String surname) { ... }
private User user(String firstname) { ---}
private final Set<User> users;
Role(User... users) {
if (users.length == 1) { ...
}
this.users = new HashSet<>();
Collections.addAll(users);
}
public boolean ...(...) {
...
}
}