为什么不从Enum扩展?E扩展Enum?E? [英] Why not extending from Enum<E extends Enum<E>>

查看:105
本文介绍了为什么不从Enum扩展?E扩展Enum?E?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绊倒了以下问题,我无法从Java 1.5(java.lang包)中定义的这个类扩展和实现。

  public abstract class Enum< E extends Enum< E>> {... 
} ..

我遇到的问题是创建自己的枚举类型具有不同的序数值。我不想使用getCode()等不同的序数来实现它,所以我以为我可以去扩展上面的类。

  public final class XYZ extends Enum< XYZ> {//不行
//
A(A,1),
B(B,7);

}

我知道我可以执行以下操作:

  public enum NEWEnum {
A(1),
B(7);

私有int代码;
private NEWEnum(int code){
this.code = code;
}
public int getCode(){
return this.code;
}
}

我宁愿在Enum中有一般的名词ordinal()和name()而不是。

解决方案

它是内置到编译器,或运行时(不确定哪个)。



但是,它看起来像是要解决错误的问题;枚举值的序数不应该具有任何功能意义。一旦你给它一个,它应该有一个不同于Ordinal的名称。你的第二个代码片段远远优于你的第一个代码片段。



总的来说,依靠任何事情都是不好的做法;它可能永远不应该暴露在第一位。你唯一可以依靠的就是名字,以及你自己分配的任何价值。



如果对你的字段命名是很重要的,只需使用 typesafe枚举模式(项目21),该枚举只是一个。


I stumbled over the following problem that i can't extend and implement from this class which is defined in Java 1.5 (java.lang package)

public abstract class Enum<E extends Enum<E>> {...
}..

The problem i have is to create my own enum type which has different ordinal values. I don't want to implement it by using different name of ordinal like getCode() etc. So i thought i could go the way to extend the above class.

public final class XYZ extends Enum<XYZ> { //Does not work.
  //
  A("A", 1),
  B("B", 7);
  .
}

I know that i can do the following:

public enum NEWEnum {
   A(1),
   B(7);

   private int code;
   private NEWEnum(int code) {
     this.code = code;
   }
   public int getCode() {
     return this.code;
   }
}

I would prefer to have the usual namings in Enum's like ordinal() and name() instead.

解决方案

You can't extend Enum like that. It's built in to the compiler, or the runtime (not sure which).

But it looks like you're trying to solve the wrong issue; the ordinal of an enum value is not supposed to have any functional meaning. As soon as you give it one, it should have a different name than 'Ordinal'. Your second code snippet is far superior to your first one.

In general, relying on ordinal for anything is bad practice; it probably never should've been exposed in the first place. The only thing you can rely on is the name, and any value you assign yourself.

If it's that important to you to name your field 'ordinal', just use the typesafe enum pattern (item 21), which Enum is just an implementation of.

这篇关于为什么不从Enum扩展?E扩展Enum?E?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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