我需要为我的应用程序创建一个元素库。Java枚举 - 返回字符串
这是我创建的类。现在
public class Elements
{
public enum Type1
{
A ("text1"),
B ("text2"),
C ("text3"),
D ("text4"),
E ("text5");
private String identifier;
Type1(String identifier)
{
this.identifier = identifier;
}
getPath()
{
String path = "";
//do something
return path;
}
}
}
我可以用Elements.type1.A.getPath();
我做Elements.type1的静态导入访问的价值观和我想删除的getPath()的使用,因为它会我的代码复杂化。即。我需要能够使用type1.A
。
所以,我没有,
public class Elements
{
public enum Type1
{
A
{
public String toString()
{
return getPath("text1");
}
},
B
{
public String toString()
{
return getPath("text2");
}
},
C
{
public String toString()
{
return getPath("text3");
}
};
Type1() {}
}
}
现在我可以用Elements.Type1.A
与打印报表,但我有一个接受String作为参数的方法。
因此,这使得它Elements.Type1.A.toString()
。没有toString(),它会抛出一个错误。
有没有办法摆脱toString()
?
编辑:新代码
public Interface Type1
{
String A = "text1";
String B = "text2";
String C = "text3";
}
public class Utility
{
public static void main(String[] args)
{
getPath(Type1.A);
}
public static void getPath(String arg)
{
//Constructs xpath - text1 changes to //*[contains(@class,'text1')]
return xpath;
}
}
public class myClass
{
public void doSomething()
{
assertEquals(Type1.A,xpath);
}
}
这里,Type1.A返回 “text1” 中,而不是// * [包含(@类, '文本1')]
您可以避免使用'toString()'的唯一原因通常是因为'+'和System.out/System.err知道如何在封面。 –
首先不要使用'toString'来返回除了'对象的字符串表示'之外的东西。这个班的客户怎么知道这实际上是一些'路径'? 而对于你的问题,你可以重载你的方法采取枚举参数,从中提取必要的属性,并将其传递给原始方法。 – zvez
对不起,这是我的错。编辑代码。 – aradhak