Reputation: 836
I need to create an element repository for my app.
This is the class I created.
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;
}
}
}
Now I can access the values using Elements.type1.A.getPath();
I did a static import of Elements.type1 and I want to remove the usage of getPath() because it would complicate my code. ie. I need to be able to use type1.A
.
So I did,
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() {}
}
}
Now I can use Elements.Type1.A
with print statements but I have a method which accepts String as parameter.
So that makes it Elements.Type1.A.toString()
. Without toString(), it throws an error.
Is there a method to get rid of toString()
?
Edit : New Code
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);
}
}
Here, Type1.A returns "text1" and not //*[contains(@class,'text1')]
Upvotes: 0
Views: 2869
Reputation: 533492
It appears you need three String constants not enums.
public static final String A = "test1";
public static final String B = "test2";
public static final String C = "test3";
Using an interface is not always best, but without further context I can't suggest something better
public interface Type1 {
String A = "test1";
String B = "test2";
String C = "test3";
}
Upvotes: 3
Reputation: 213223
Well, as Peter
said, you need final static
variables here..
Looks, like you want a set of String Constants
to work with.. Then definitely you should work with what Peter
has quoted..
Just to extends what he said, you can create an Interface, and have all your String Constants in it.. Then you can easily access them through Interface
name..
public Interface Type1 {
String A = "text1";
String B = "text2";
String C = "text3";
}
And somewhere in your other class: -
public class Utility {
public static void main(String[] args) {
// You can pass your String to any method..
String a = Type1.A;
getPath(a);
getPath(Type1.B);
}
// This method is not doing work according to its name..
// I have just taken an example, you can use this method to do what you want.
public static void getPath(String arg) {
// You can process your string here.
arg = arg + "Hello";
}
}
You can also change what your toString()
returns based on your needs..
And follow Java Naming Convention
.. Enums, Classes start with Uppercase
letters..
Upvotes: 3