gpt4 book ai didi

Java - 将字符串映射到带有枚举的接口(interface)的实现?

转载 作者:行者123 更新时间:2023-11-30 09:30:10 28 4
gpt4 key购买 nike

在我的遗留代码中,我有一个属性/值对的概念。

每个属性/值在我的系统中都有一些任意的含义。所以,我的接口(interface)有方法 getValue() 和 setValue()。其中每一个都根据属性在我的系统中的含义执行一些特定的业务逻辑。

这很好用,但我遇到了一些问题。

首先是我的映射看起来像这样:

if (name == "name1") return thisAttributeImplementation();

这是丑陋的,而且很容易搞砸打字......

第二个是这些 AttributeImplementations 需要知道它们的属性名称,但它们不知道,除非我将它作为静态成员提供,或者将它传递给构造函数,这两者都很丑陋。

枚举似乎是解决这两个问题的好方法,但我在处理后勤问题时遇到了麻烦。为了将字符串与对象相关联,枚举应该是什么样子?我应该如何遍历枚举以找到合适的枚举?对象本身应该如何获得与其关联的字符串的知识?

最佳答案

与此类似的东西是否正确?

public enum Borough {
MANHATTAN(1),
THE_BRONX(2),
BROOKLYN(3),
QUEENS(4),
STATEN_ISLAND(5);

private int code;

private Borough(final int aCode) {
code = aCode;
}

/**
* Returns the borough associated with the code, or else null if the code is not that of a valid borough, e.g., 0.
*
* @param aCode
* @return
*/
public static Borough findByCode(final int aCode) {
for (final Borough borough : values()) {
if (borough.code == aCode) {
return borough;
}
}
return null;
}

/**
* Returns the borough associated with the string, or else null if the string is not that of a valid borough, e.g., "Westchester".
*
* @param sBorough
* @return
*/
public static Borough findByName(final String sBorough) {

for (final Borough borough : values()) {
if (borough.name().equals(sBorough)) {
return borough;
}
}
return null;
}

public int fromEnumToInt() {
return mId;
}


}

关于Java - 将字符串映射到带有枚举的接口(interface)的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368188/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com