Search code examples
javaconstants

Java | Use constant and check if a value equals one of them


I have this class to hold my constants:

public class UserRole {
    static final String ADMIN = "Admin";
    static final String SELLER = "Seller";
    static final String BIDDER = "Bidder"; 
}

When Im getting input from the user I want to check that input.toLower() equals to one of this constants.
(I want the class to provide such a method) I can do it with multiple ifs of course but i want it to be more elegant. I gonna use a lot of constants in my code and that w'd probably produce a more elegant code that easier to debug and read. Im coming from the C++ world where i can use x-macros or something similar and i'd like to know what is a good way to achieve this task in Java.


Solution

  • Enum

    I gonna use a lot of constants in my code and that w'd probably produce a more elegant code that easier to debug and read.

    For constants known at compile time, an enum is often the best approach. The enum facility in Java is more powerful and flexible than you may have seen in other languages.

    In Java, each enum object is named in all-uppercase, by convention.

    enum UserRole
    {
        ADMIN ,
        SELLER , 
        BIDDER ;
     }
    

    Fetch by constant name.

    UserRole userRole = UserRole.valueOf( UserRole.class , "seller".toUpperCase() ) ;
    

    See that code run at Ideone.com.

    userRole.toString() = SELLER

    Or, you may want to add a display name for presentation to the users.

    Add a private member field to the enum class. Write a constructor that takes the text of each enum object’s display name. Add a getter method. And write a static method to look for the enum matching an expected display name.

    enum UserRole
    {
        ADMIN ( "Admin" ) ,
        SELLER ( "Seller" ) , 
        BIDDER ( "Bidder" ) ;
    
        private final String displayName ;
    
        // Constructor 
        UserRole ( String displayName ) 
        {
            this.displayName = displayName ;
        }
    
        public String getDisplayName() 
        { 
            return this.displayName ; 
        }
    
        public static UserRole forDisplayNameIgnoreCase ( final String desiredDisplayName ) 
        {
            for ( UserRole userRole : UserRole.values() )
            {
                if ( userRole.getDisplayName().equalsIgnoreCase( desiredDisplayName ) )
                {
                    return userRole ;
                }
            }
            throw new IllegalArgumentException( "Unknown display name" ) ;  // Or return an `Optional< UserRole >`. The Optional would be my preference. 
        }
    
    }
    

    Fetch by display name.

    UserRole userRole = UserRole.forDisplayNameIgnoreCase ( "seller" ) ;
    

    See this code run at Ideone.com.

    userRole.toString() = SELLER