为什么要在枚举内部创建一个枚举?
Table.java
public enum Table {
CREATE("CREATE TABLE"),
ALTER("ALTER TABLE");
private String cmd;
Table(String cmd) {
this.cmd = cmd;
}
@Override
public String toString() {
return cmd;
}
}
Database.java
public enum Database {
CREATE("CREATE DATABASE");
private String cmd;
Database(String cmd) {
this.cmd = cmd;
}
@Override
public String toString() {
return cmd;
}
}
在这个例子中,
System.out.println(Table.CREATE);
会输出
CREATE TABLE
。
这也有助于代码的可读性,因为你可以生成像这样的代码:
String query = Table.CREATE + "(Column1 " + DbType.INTEGER + " " + Column.UNIQUE + " " + Column.PRIMARY_KEY + ")";
在我看来,这样会更容易阅读和理解。
编辑
为了尝试接近你想要的效果,你可以做一些类似的事情:
public enum SQL {
TABLE("TABLE", SQL.CREATE_FLAG | SQL.ALTER_FLAG),
DATABASE("DATABASE", SQL.CREATE_FLAG);
public static final int CREATE_FLAG = 1;
public static final int ALTER_FLAG = 2;
public static final String CREATE_STRING = "CREATE";
public static final String ALTER_STRING = "ALTER";
public static final String INVALID = "INVALID";
private String name;
private boolean create;
private boolean alter;
SQL(String name, int flags) {
create = (flags & CREATE_FLAG) != 0;
alter = (flags & ALTER_FLAG) != 0;
this.name = name;
}
public String create() {
if (create)
return CREATE_STRING + " " + name;
else
return INVALID;
}
public String alter() {
if (alter)
return ALTER_STRING + " " + name;
else
return INVALID;
}
}
你可以调用的地方:
System.out.println(SQL.TABLE.create()); // CREATE TABLE
System.out.println(SQL.TABLE.alter()); // ALTER TABLE
System.out.println(SQL.DATABASE.alter()); // INVALID
System.out.println(SQL.DATABASE.create()); // CREATE DATABASE