最好的方法来创buildstring的枚举?

有一个enumtypes代表一组string的最佳方式是什么?

我试过这个:

 enum Strings{ STRING_ONE("ONE"), STRING_TWO("TWO") } 

我怎样才能把它们用作Strings

我不知道你想要做什么,但这是我如何真正的翻译你的示例代码….

 /** * */ package test; /** * @author The Elite Gentleman * */ public enum Strings { STRING_ONE("ONE"), STRING_TWO("TWO") ; private final String text; /** * @param text */ private Strings(final String text) { this.text = text; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return text; } } 

或者,您可以为text创build一个getter方法。

你现在可以做Strings.STRING_ONE.toString();

Enum的自定义string值

来自http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

Java枚举的默认string值是它的面值或元素名称。 但是,您可以通过覆盖toString()方法来自定义string值。 例如,

 public enum MyType { ONE { public String toString() { return "this is one"; } }, TWO { public String toString() { return "this is two"; } } } 

运行下面的testing代码将产生这个:

 public class EnumTest { public static void main(String[] args) { System.out.println(MyType.ONE); System.out.println(MyType.TWO); } } this is one this is two 

使用其name()方法:

 public class Main { public static void main(String[] args) throws Exception { System.out.println(Strings.ONE.name()); } } enum Strings { ONE, TWO, THREE } 

产生ONE

根据你的意思是“用它们作为string”,你可能不想在这里使用枚举。 在大多数情况下,精英绅士提出的解决scheme将允许您通过他们的toString方法使用它们,例如System.out.println(STRING_ONE)String s = "Hello "+STRING_TWO ,但是当您真的需要Strings例如STRING_ONE.toLowerCase() ),您可能更喜欢将它们定义为常量:

 public interface Strings{ public static final String STRING_ONE = "ONE"; public static final String STRING_TWO = "TWO"; } 

将枚举名称设置为与所需的string相同,或者更一般地说,可以将任意属性与您的枚举值相关联:

 enum Strings { STRING_ONE("ONE"), STRING_TWO("TWO"); private final String stringValue; Strings(final String s) { stringValue = s; } public String toString() { return stringValue; } // further methods, attributes, etc. } 

顶部有常量,底部有方法/属性是很重要的。

如果你不想使用构造函数 ,并且想为该方法指定一个特殊的名字 ,可以试试这个:

 public enum MyType { ONE { public String getDescription() { return "this is one"; } }, TWO { public String getDescription() { return "this is two"; } }; public abstract String getDescription(); } 

我怀疑这是最快的解决scheme。 最后不需要使用variables

你可以使用它的string枚举

 public enum EnumTest { NAME_ONE("Name 1"), NAME_TWO("Name 2"); private final String name; /** * @param name */ private EnumTest(final String name) { this.name = name; } public String getName() { return name; } 

}

并从主要方法调用

公共类testing{

 public static void main (String args[]){ System.out.println(EnumTest.NAME_ONE.getName()); System.out.println(EnumTest.NAME_TWO.getName()); } 

}