Java 静态类/常量字段层次结构-可以这样做吗?

Java 静态类/常量字段层次结构-可以这样做吗?,java,oop,static,hierarchy,Java,Oop,Static,Hierarchy,我试图为我的数据库表实现一个很好的抽象。我期待的结果是能够做到这一点: System.out.println(Table.Appointment); // prints the name of the table System.out.println(Table.Appointment.ID); // prints the name of the column 这里是我接近的内容,但字段似乎优先于静态内部类 public class Table { // attempt to

我试图为我的数据库表实现一个很好的抽象。我期待的结果是能够做到这一点:

System.out.println(Table.Appointment);    // prints the name of the table 
System.out.println(Table.Appointment.ID); // prints the name of the column
这里是我接近的内容,但字段似乎优先于静态内部类

public class Table {

    // attempt to allow 'Table.Appointment' to resolve to a String
    public static final Table Appointment = new Table("Appointment");

    // attempt to give access to column names within the table,
    // these class names should be the same as its name field above.
    public static final class Appointment{
        public static final String ID = "AppointmentId";
    };

    private String name; 
    private Table(String name){ this.name = name; }
    public String toString() { return name; }
}

这真的可以实现吗?

虽然我强烈反对您这样做,只是因为这会使您的应用程序过于坚固,但这是可行的(编辑以避免循环引用):

编译器会抱怨
foo
没有初始化。这是因为声明一个变量不会给它分配任何内容(你声明了一个名为
foo
int
类型的容器),除非你给它分配了内容,否则它不会保存任何内容

Table appointment = new Table("appointment" // table name
                            , "appointmentId"  // id column name);

System.out.println(appointment.getTableName());    
System.out.println(appointment.getIdColumnName()); 
如果你想把事情推到编译时,你可以使用子类

class Appointment extends Table{
    Appointment(){  super("appointment", "appointmentId"); }
}

因此,重命名实例变量-不要因为这个原因而将它们大写。要为任务使用枚举,bit为什么不使用jpa元模型?@Jake223我一直是命名约定的执行者,但对于这项任务,我希望它们与静态类名保持一致。@guido我有一个版本,我尝试使用枚举,但没有走得很远。我现在将查找jpa元模型。为什么这两条语句中层次结构的一致性比世界其他地方读取Java代码的一致性更重要?尤其是当层次结构没有真正映射到Java的层次结构时。内部类只是名称空间,不定义任何关系。这违背了问题的全部要点。在默认get方法中使用泛型名称非常容易。这很有趣,但是会导致如下调用:
Table.AppointmentTable.ID
Table.Appointment
。这也很接近,但我仍然好奇是否有一个完全一致的解决方案。我编辑了我的示例,删除了循环表引用,并使所有内容都成为最终结果。我认为你不可能实现与你期望的更接近的目标。我确实补充了一些澄清。如果你需要更多的解释,只需评论。
Table appointment = new Table("appointment" // table name
                            , "appointmentId"  // id column name);

System.out.println(appointment.getTableName());    
System.out.println(appointment.getIdColumnName()); 
class Appointment extends Table{
    Appointment(){  super("appointment", "appointmentId"); }
}