1

在 java 1.8 中运行的应用程序必须在 java 1.4 的几个盒子中运行。该应用程序使用了大量常量(数以千计),并且所有内容都使用函数枚举来实现。使其反向兼容的最佳方法是什么?

编辑 :

我已经看到了几个答案,但没有一个是令人满意的。因此,为了明确我在这里想要实现的目标,请看下面的一个小例子

public class SomeType
{
    public enum TYPE
    {
        ERROR("allError","4"),
    INPUT("allInput","5"),
        OFFLINE("allOffline","6"),;

        private final String type;
        private final String desc;

        TYPE(String type, String desc)
        {
            this.type = type;
            this.desc = desc;
        }
        public String getType(){
            return this.type;
        }
        public String getDesc(){
            return this.type;
        }
    }
}
}

这将被类似的东西消耗

for (SomeType.TYPE type: SomeType.TYPE.values())
        {
            if(nodeValue.equalsIgnoreCase(type.getType()))
            {
                value=type.getDesc();
                break;
            }
        }

所以这在 1.4 中永远不会兼容,所以我必须编写很多样板代码,正如@Gene 在他提供的链接中所解释的那样。由于有很多像这样的类在其中包含非常大的常量列表,我觉得需要一种更好的方法。所以问题是寻找更好的解决方案。

4

1 回答 1

1

您可以在所有使用枚举的地方使用接口 - 这样您就不必更改 Java 5+ 中的枚举实现。

public interface Type {
   String getDesc();
   String getType();
}

Java 5+ 中的接口实现将是相同的:

public enum TYPE implements Type
{
    ERROR("allError","4"),
    INPUT("allInput","5"),
    OFFLINE("allOffline","6"),;

    private final String type;
    private final String desc;

    TYPE(String type, String desc)
    {
        this.type = type;
        this.desc = desc;
    }
    public String getType(){
        return this.type;
    }
    public String getDesc(){
        return this.type;
    }
}

在 Java 5 中,您必须使用来自 apache-commons 的 Enum 或自定义实现来实现类型(最好的方法是使用一些代码生成器来获取枚举并将其转换为 Java 5 之前的类)

消费代码:

for (Type type: types)
    {
        if(nodeValue.equalsIgnoreCase(type.getType()))
        {
            value=type.getDesc();
            break;
        }
    }

其中类型是类型 []。我不知道你是否使用 switch 语句,但循环可以正常工作。

因此,这样您就不必为枚举使用者提供单独的代码,但仍需要将枚举重写为 Enum。

于 2016-04-19T09:45:25.197 回答