本文介绍了Java枚举 - 在定义之前不能引用字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似下面的枚举,但eclipse说每个相对对的第一个定义有错误。

  public enum Baz {
yin(yang),//在定义之前无法引用字段
yang(yin),
good(evil),//在定义之前不能引用一个字段
evil(good);

public final Baz对面;

Baz(Baz对面){
this.opposite =对面;
}
}

我想要完成的是能够使用 Baz.something.opposite 以获得 Baz.something 的相对对象。这有可能的解决方法吗?也许在 yang 和之前的空白占位符之前 yin 和 good 在本例中定义

解决方案

  public enum Baz {
yin(yang),
yang(yin) ,
good(evil),
evil(good);

private String对面;

Baz(String对面){
this.opposite =对面;
}

public Baz getOpposite(){
return Baz.valueOf(opposite);
}
}

然后将其引用为

  Baz.something.getOpposite()

这应该通过查找枚举值来完成你想要做的,它的字符串表示形式。我不认为你可以使用Baz的递归参考。


I have an enum like the one below, but eclipse says that there are errors in the first definition of each opposite pair.

public enum Baz{
  yin(yang),    //Cannot reference a field before it is defined
  yang(yin),
  good(evil),   //Cannot reference a field before it is defined
  evil(good);

  public final Baz opposite;

  Baz(Baz opposite){
    this.opposite = opposite;
  }
}

What I want to accomplish is being able to use Baz.something.opposite to get the opposite object of Baz.something. Is there a possible workaround for this? Maybe an empty placeholder for yang and bad before yin and good are defined in this example?

解决方案

You could try something like:

public enum Baz{
  yin("yang"),
  yang("yin"),
  good("evil"),
  evil("good");

  private String opposite;

  Baz(String opposite){
    this.opposite = opposite;
  }

  public Baz getOpposite(){
     return Baz.valueOf(opposite);
  }
}

and then reference it as

Baz.something.getOpposite()

That should accomplish what you are looking to do by looking up the enum value by it's string representation. I don't think you can get it to work with the recursive reference to Baz.

这篇关于Java枚举 - 在定义之前不能引用字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:45