Java | 使用常量并检查一个值是否等于它们之一

huangapple go评论56阅读模式
英文:

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

问题

我有这个类来保存我的常量:

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

当我从用户获取输入时,我想要检查 input.toLower() 是否等于这些常量之一。我希望这个类提供这样的方法。
当然,我可以使用多个 if 来实现,但我想要更加优雅的方法。我将在我的代码中使用许多常量,这可能会产生更加优雅、易于调试和阅读的代码。
我来自C++世界,在那里我可以使用 x-macros 或类似的东西,我想知道在Java中实现这个任务的好方法是什么。

英文:

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.<br/> (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.

答案1

得分: 2

枚举

> 我会在我的代码中使用很多常量,这可能会产生更优雅、更易于调试和阅读的代码。

对于在编译时已知的常量,通常最好的方法是使用枚举。Java中的枚举功能比您在其他语言中看到的更强大和灵活。

在Java中,按照惯例,每个枚举对象的名称都采用大写字母。

enum UserRole
{
    ADMIN,
    SELLER,
    BIDDER;
}

通过常量名称获取枚举对象。

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

查看这个在 Ideone.com 上运行的代码

>userRole.toString() = SELLER

或者,您可能希望为用户添加一个显示名称。

为枚举类添加一个私有成员字段。编写一个构造函数,该构造函数接受每个枚举对象的显示名称文本。添加一个获取器方法。并编写一个查找与期望的显示名称匹配的枚举的static方法。

enum UserRole
{
    ADMIN("Admin"),
    SELLER("Seller"),
    BIDDER("Bidder");

    private final String displayName;

    // 构造函数 
    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("未知的显示名称");  // 或者返回一个 `Optional<UserRole>`。Optional 是我更偏向的选择。
    }

}

通过显示名称获取枚举。

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

查看这个在 Ideone.com 上运行的代码

>userRole.toString() = SELLER

英文:

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 , &quot;seller&quot;.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 ( &quot;Admin&quot; ) ,
    SELLER ( &quot;Seller&quot; ) , 
    BIDDER ( &quot;Bidder&quot; ) ;

    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( &quot;Unknown display name&quot; ) ;  // Or return an `Optional&lt; UserRole &gt;`. The Optional would be my preference. 
    }

}

Fetch by display name.

UserRole userRole = UserRole.forDisplayNameIgnoreCase ( &quot;seller&quot; ) ;

See this code run at Ideone.com.

>userRole.toString() = SELLER

答案2

得分: 1

这不是一个好主意,将输入与常量字段进行匹配。您可以使用映射来匹配这样的数据。不过,如果您仍然想要这样做,这里是该类。

import java.lang.reflect.Field;

public class ConstantCheckerUtil {
    public static boolean checkConstant(String input) {
        boolean hasAnyMatch = false;

        try {
            Class<UserRole> userRoleClass = UserRole.class;
            Field[] userRoleClassDeclaredFields = userRoleClass.getDeclaredFields();
            for (Field userRoleClassDeclaredField : userRoleClassDeclaredFields) {
                if(userRoleClassDeclaredField.get(userRoleClassDeclaredField.toString()).toString().toLowerCase().equals(input)) {
                    hasAnyMatch = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); //您可以增强日志记录部分
        }

        return hasAnyMatch;
    }

    public static void main(String[] args) { //测试
        System.out.println(ConstantCheckerUtil.checkConstant("Admin".toLowerCase()));
    }
}
英文:

It is not a good idea to match the input against the constants fields. You could use map to match such data. However, still if you want to do it, here is the class.

import java.lang.reflect.Field;

public class ConstantCheckerUtil {
    public static boolean checkConstant(String input) {
        boolean hasAnyMatch = false;

        try {
            Class&lt;UserRole&gt; userRoleClass = UserRole.class;
            Field[] userRoleClassDeclaredFields = userRoleClass.getDeclaredFields();
            for (Field userRoleClassDeclaredField : userRoleClassDeclaredFields) {
                if(userRoleClassDeclaredField.get(userRoleClassDeclaredField.toString()).toString().toLowerCase().equals(input)) {
                    hasAnyMatch = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); //You can enhance the logging part
        }

        return hasAnyMatch;
    }

    public static void main(String[] args) { //Testing
        System.out.println(ConstantCheckerUtil.checkConstant(&quot;Admin&quot;.toLowerCase()));
    }
}

huangapple
  • 本文由 发表于 2023年3月3日 22:29:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定