我需要爲我的應用程序創建一個元素庫。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