列挙型を一般的に回避する作業の多くを行うのは比較的簡単です。
これは、大幅に削減された例です。定義型としてTable
を取る汎用データベースクラスを定義します。enum Column
は、テーブル内のenum
列を定義します。定義型はenum
、非常に便利なトリックであるインターフェースも実装する です。
public class Table<Column extends Enum<Column> & Table.Columns> {
// Name of the table.
protected final String tableName;
// All of the columns in the table. This is actually an EnumSet so very efficient.
protected final Set<Column> columns;
/**
* The base interface for all Column enums.
*/
public interface Columns {
// What type does it have in the database?
public Type getType();
}
// Small list of database types.
public enum Type {
String, Number, Date;
}
public Table(String tableName,
Set<Column> columns) {
this.tableName = tableName;
this.columns = columns;
}
}
次のようなものを使用して、実際のテーブルを作成できます。
public class VersionTable extends Table<VersionTable.Column> {
public enum Column implements Table.Columns {
Version(Table.Type.String),
ReleaseDate(Table.Type.Date);
final Table.Type type;
Column(Table.Type type) {
this.type = type;
}
@Override
public Type getType() {
return type;
}
}
public VersionTable() {
super("Versions", EnumSet.allOf(Column.class));
}
}
これは本当に些細な例ですが、少し手を加えるだけで、多くのenum
作業を親クラスに簡単に移動できることに注意してください。
この手法は、ジェネリックを使用するときに取得するタイプ セーフ チェックを保持します。