Java:抽象枚举常量 [英] Java: abstract enum constant

查看:56
本文介绍了Java:抽象枚举常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以将抽象枚举声明为函数参数?我要实现的目标是:

Is there a way to declare an abstract enum as a function parameter? What I'm trying to achieve is this:

interface EnumInterpreterInterface {
   String getStringValue(**abstract enum constant** e);
}

interface EnumProviderInterface {
    //classes implementing this interface will hold at least one enum
    Enum getEnum();
}

class EnumProvider implements EnumProviderInterface {
    enum Numbers {ONE, TWO, THREE};
}

class EnumInterpreter implements EnumInterpreterInterface {
   String getStringValue(EnumProvider.Numbers n) {
       switch(e) {
           case EnumProvider.Numbers.ONE: return "one";
           case EnumProvider.Numbers.TWO: return "two";
           default: return "three";
       }
   }
}

推荐答案

如果您想要的是抽象枚举,则可以执行以下操作:

If what you want is an abstract Enum you can do this :

interface EnumInterpreterInterface {
    String getStringValue(Enum<?> e);
}

由于Enum是抽象类,因此可以用作任何类.

Since Enum is an abstract class it can be used as any class.

但是必须注意实现,请考虑此类:

But attention has to be made for the implementations, consider this class :

class EnumInterpreter implements EnumInterpreterInterface { code }

然后将像这样实现getStringValue:

Then getStringValue would be implemented like this :

String getStringValue(Enum n) 
{
   if(n instanceof EnumProvider.Numbers)
   {
       EnumProvider.Numbers e=(EnumProvider.Numbers)n;
       switch(e) {
            case ONE: return "one";
            case TWO: return "two";
            default: return "three";
       }
   }
   else //do something, maybe return null or throw an exception
}

请注意,您不能将签名更改为此 String getStringValue(EnumProvider.Numbers n),因为编译器会抱怨(尽管枚举是返回值,但不会抱怨).

Note that you can't change the signature into this String getStringValue(EnumProvider.Numbers n) because the compiler will complain(it wouldn't complain if the enum was the return value though).

并且因为我们不能在签名中限制Enum类型,所以我们必须使用 instanceof 进行检查并进行强制转换.

And because we can't restrict the Enum type in the signature we have to check with instanceof and cast.

是类,因此上面的代码起作用.但是,对于其他可能不是这样的编程语言(例如,C#,C ++中的枚举通过整数表示),在我的卑鄙知识中,没有任何方法可以做到这一点:).

in java enums are classes, that's why the above code works. However, for other programming languages that may not be the case(enums in C#,C++ for example are represented via integers) in which there isn't any way to do this in my humble knowledge :).

这篇关于Java:抽象枚举常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆