【问题标题】:Implementing enum for reverse compatibility实现枚举以实现反向兼容性
【发布时间】:2016-04-19 02:50:10
【问题描述】:

在 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 在他提供的链接中所解释的那样。由于有很多像这样的类在其中包含非常大的常量列表,我觉得需要一种更好的方法。所以问题是寻找更好的解决方案。

【问题讨论】:

  • 我在这个答案中展示了如何复制枚举的大部分功能(包括成员方法):stackoverflow.com/questions/4709175/…。这种技术不能做的主要事情是与switch 很好地配合。但是你打开了一个标量成员值。
  • @11thdimension 我确实看到了这个。但在切换案例方面,我的问题更多。
  • @Gene 你的回答更好地解释了它。正如您在回答中提到的那样,我“不开心”!但我想我将不得不忍受这一点。
  • 生成 1.4 源的源转换似乎最灵活。存在枚举反向移植,但应该进行转换。

标签: java enums compatibility java1.4 backport


【解决方案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 或自定义实现来实现 Type(最好是使用一些代码生成器获取枚举并将其转换为 Java 5 之前的类)

消费代码:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多