Options/enums in java?
Is there a best practice for enumerations in java? For example, I have the following:
class Foo {
public static final int OPTION_1 = 'a';
public static final int OPTION_2 = 'b';
public void doSomething(String name, int option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.doSomething("blah", Foo.开发者_如何学PythonOPTION_2);
}
so the user can choose to use one of the static ints defined in Foo, but they could also supply any other int they want, there's no compile-time checking on it. Is there some way around this in java, some other way of doing this to restrict the end developer to choose from only the defined option types?
Thanks
class Foo {
public enum Option{First, Second}
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Foo.Option.Second);
}
Since Java 1.5 there is the enum keyword which makes typesafe enumerations
Your code would look like this then :
class Foo {
public enum Option = { OPTION_1, OPTION_2 };
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.doSomething("blah", Foo.Option.OPTION_2);
}
This is fully supported by the type system so the compiler will enforce the user not to become to creative when passing options.
You can read more here
There are enum types in Java (as of J2SE 5.0). Read the tutorial.
public enum Option{
OPTION_1, OPTION_2 //All caps by convention
}
class Foo {
public void dosomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Option.OPTION_2);
}
you even can add method into enum, check it out at sun document http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
This will allow you to set the value of the enum
enum Option{
ONE('a');
TWO('b');
private Option(int x){
value = x;
}
private int value;
}
class Foo {
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Option.ONE);
}
精彩评论