Why my OUTPUT is showing NOOOO?
UserRole.java
public enum UserRole {
ROLE_X("ROLE_X"), //
ROLE_Y("ROLE_Y"), //
ROLE_Z("ROLE_Z"), //
OTHER_X("OTHER_X"),
OTHER_Y("OTHER_Y"),
OTHER_Z("OTHER_Z");
private final String name;
private UserRole(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean hasName(String name) {
return this.name.equals(name);
}
public static UserRole[] ROLES = { ROLE_X, ROLE_Y, ROLE_Z };
public static UserRole[] OTHER = { OTHER_X, OTHER_Y, OTHER_Z };
}
TestCode.java
import java.text.ParseException;
import org.apache.commons.lang.ArrayUtils;
public class TestCode{
public static void main(String[] args) throws ParseException {
String name = "ROLE_X";
if(ArrayUtils.contains(UserRole.ROLES, name)) {
System.out.println("---ROLES---");
} else {
System.out.println("NOOOO");
}
}
}
OUTPUT: NOOOO
Because an enum is not a String.
You have an array of enum instances, but you're searching for a String, which will never be equals() to an enum.
Use:
UserRole.valueOf(str)
and catch IllegalArgumentException, which is thrown when the string doesn't match an instance.
Most of your enum class can be deleted:
name field at all. Every enum has a .name() method that returns the enum instance name as a string.values() method that returns all instances as an arrayIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With