在我的遗留代码中,我有一个属性/值对的概念。
每个属性/值在我的系统中都有一些任意的含义。因此,我的接口(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/