作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的遗留代码中,我有一个属性/值对的概念。
每个属性/值在我的系统中都有一些任意的含义。所以,我的接口(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/
我是一名优秀的程序员,十分优秀!