【问题标题】:Parametrize annotation value参数化注释值
【发布时间】:2023-04-08 19:38:01
【问题描述】:

我有两个类使用注释来定义字段和数据库列名之间的链接。除了它们定义的列名之外,这些类非常相似:

class TableA {
    @ForeignName("IDTableA") // Column name in TableC referring to this TableA record
    List<TableC> elements;
    // Some other field definitions, common between TableA and TableB

    // Some other field definitions, specific to TableA
}

class TableB {
    @ForeignName("IDTableB") // Column name in TableC referring to this TableB record
    List<TableC> elements;
    // Some other field definitions, common between TableA and TableB

    // Some other field definitions, specific to TableB
}

class TableC {
    @LocalName("IDTableA")
    TableA refA;
    @LocalName("IDTableB")
    TableB refB;
}

我想有一个超类,我可以给它"IDTableA/B" 常量。理想情况下“类似”(我知道除了类型之外你不能给泛型提供任何东西,只是为了说明我的观点):

abstract class TableAB<IDName> {
    @ForeignName(IDName)
    List<TableC> elements;
    // Field definitions common between TableA and TableB
}

class TableA extends TableAB<"IDTableA"> {
    // Field definitions, specific to TableA
}

class TableB extends TableAB<"IDTableB"> {
    // Field definitions, specific to TableB
}

这有可能吗?

【问题讨论】:

    标签: java annotations compile-time-constant


    【解决方案1】:

    不,这是不可能的。 IDName 部分需要是一个常量,并且在任何情况下都不能提供 String 文字作为泛型类型。

    【讨论】:

    • 好的。我知道除了类型之外你不能给泛型提供任何东西,但对我来说“如果”我想做的事情是可能的。我会更新问题以使其更清楚。谢谢!
    • 嗯,问题在于@ForeignName(IDName) 需要IDName 的常量表达式。您无法让该常量表达式以某种方式动态并取决于子类。
    • 好的,我会找到其他方法。并在接受您的答案之前再等待强制性的 5 分钟。 ;)
    • @Matthieu 没问题。我自己只是更早地研究了一个相关问题,所以我知道似乎没有可行的解决方案。您也不能在注释中包含枚举值,因为它不被视为常量,即使您将其完全用作常量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多