我在代码中的很多地方进行了硬编码比较,我对此并不满意。我正在寻找正确的方法来解决这个问题。
示例
public class Status {
public static final int ACTIVE = 1,
INACTIVE = 2,
ENDED = 3,
PAUSED = 4,
NEW = 5,
INIT = 6,
STARTED = 7;
private int id;
private String name;
public int getId(){ return this.id; }
public String getName(){ return this.name; }
//get and set the object from the db by the id
public Status(int id){}
}
public class Job {
private int id;
private Status stage;
//get and set the object from the db by the id
Job(int id){}
public boolean isStageStatusEnded(){
return this.stage.getId() == Status.ENDED;
}
}
我有这个数据库表:
mysql> desc statuses;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
mysql> select * from statuses;
+----+----------+
| id | name |
+----+----------+
| 1 | ACTIVE |
| 2 | INACTIVE |
| 3 | ENDED |
| 4 | PAUSED |
| 5 | NEW |
| 6 | INIT |
| 7 | STARTED |
+----+----------+
正如您所看到的,static final int
类中的Status
是表statuses
的精确副本和return this.stage.getId() == Status.ENDED;
行的精确副本。现在,如果值在任何时候都会发生变化(id
/ name
),我也必须更改static int
。我不知道如何改变它,但如果你知道一种方式 - 分享它。
答案 0 :(得分:0)
有几种方法。这可以是其中之一:
final
关键字。使用Java反射填充常量中的值。
Field field = Status.class.getDeclaredField(name);
field.setInt(field, id);
答案 1 :(得分:0)
您仍然需要在数据库或代码中将这些值硬编码到某处,否则您将无法知道每个值的含义。之后,如果符合您的需要或加载到您的应用程序中,您可以将它们保留到数据库中。
正如保罗写的那样,你在应用程序启动时会加载来自数据库的值,但我建议使用enum
而不是许多int
常量来保存很多神经。< / p>
Here是一个有用的链接,对于常量的枚举,请阅读J.Bloch,Effective Java。