【问题标题】:Java using supertype of several enumsJava使用几个枚举的超类型
【发布时间】:2013-07-16 07:37:42
【问题描述】:

我希望能够在不同的枚举上使用超类型,代码由三部分组成:

Manager.search:

public final List<B> search(final Order order, final Field field, final AbstractConstraint... c) throws SearchException {
    if (c.length == 0) {
        throw new IllegalArgumentException("orm.Manager.search: c.length == 0");
    }
    try {
        List<B> beans = new ArrayList<>();

        for (AbstractConstraint constraint : c) {
            try (PreparedStatement ps = new QueryBuilder(connection, tableName(), getPaths(), searchQuery()).add(constraint).order(order, field).build();ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    beans.add(createBean(rs));
                }
            }
        }
        return beans;
    } catch (SQLException ex) {
        Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        throw new SearchException(ex);
    }
}

orderfield 变量在这里是最重要的。

自动生成的 TemplateAttributeField.java:

public enum TemplateAttributeField implements Field {
    templateId,
    attributeOrder,
    attributeName,
    x1,
    x2;
}

以及调用代码:

try (TemplateAttributeManager templateAttributeManager = ManagerFactory.getTemplateAttributeManager()) {
    List<TemplateAttributeBean> templateAttributes = null;
    try {
        templateAttributes = templateAttributeManager.search(Order.ASCENDING, TemplateAttributeField.attributeOrder, new TemplateAttributeConstraint.Builder().templateId(template.getTemplateId()).build());
    } catch (SearchException ex) {
        Logger.getLogger(OutputProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    for (Word word : words) {

    }
}

但是在templateAttributes = ... 我得到以下异常/错误:

no suitable method found for search(Order,TemplateAttributeField,TemplateAttributeConstraint)
    method Manager.search(Order,Field,AbstractConstraint...) is not applicable
      (actual argument TemplateAttributeField cannot be converted to Field by method invocation conversion)

Field 类不仅仅是一个不会阻止额外功能的接口。

我在这里遗漏了什么,或者我应该如何解决它?

【问题讨论】:

  • 你确定Fields 是一样的吗?如果生成代码,你确定没有第二个Field 接口生成吗?
  • 这是一个愚蠢的错误,实际上甚至与自动生成无关。我有一个orm.Fieldorm.fields.Field,随后在orm.Manager 类中我想使用orm.fields.Field,因此它会自动选择特定于包的那个。

标签: java enums supertype


【解决方案1】:

我尝试创建一个最小的工作示例,但它似乎对我有用。如果这对您有用并且符合您的要求,您可以试试吗?

public class Test {
    static interface I {}
    static enum E implements I {A}
    static void m(I i) {}

    public static void main(String[] args) {
        m(E.A);
    }
}

还要确保在 enum 中实现与方法中所需的相同的 Field 接口。也许存在名称冲突,并且您使用的是来自不同包的接口。

【讨论】:

  • 应该按预期工作,我在 OP 上评论了一个讨厌的错误。
  • 好吧,刚刚也想到了这个问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多