Java 注释 - 对象数组或 toString 值

标签 java annotations coding-style

我需要编写一个注释来从结果集中排除某些值。

背景:

不同的值从字段中选择并列在组合框中。一些遗留值已弃用,我不想显示它们,即使它们由 JDBC 的 SELECT DISTINCT() 返回也是如此。它就像一个迷你框架,人们可以在其中通过单击组合框中的值来构建选择查询。

我尝试了以下方法(代码无法编译 - 注释行是我尝试解决问题的方法):

public enum JobType {
    //...
    S,
    //...
}

public @interface Exclude {
    Object[] values(); // Invalid type
    Enum[] values(); // Invalid type again
    String[] values(); // Accepts but see the following lines
}

@Table(name = "jobs_view")
public class JobSelectionView extends View {
    //...
    @Exclude(values = {JobType.S.toString()}) // Not a constant expression
    @Exclude(values = {JobType.S.name()}) // Not a constant expression ?!?!?!
    @Exclude(values = {"S"}) // Works but... come on!
    @Enumerated(value = EnumType.STRING)
    @Column(name = "type")
    private JobType type;
    //...
}

我不喜欢使用 {"S"},有什么建议吗?

最佳答案

But if declare JobType[] values() then I won't be able to reuse the @Exclude for other types of Enum.

不过,这是执行您想要的操作的最佳方式。事情是这样的:

Enum 类本身没有意义。

它只有在被子类化时才有意义。假设您要添加另一个过滤器,比如 Color(您自己的自定义 Color 枚举,而不是 java.awt.Color)。显然,您的过滤类所做的事情对于过滤掉 JobType 与过滤掉 Color 非常不同!

因此,最好的办法是让每个不同的 enum 尝试过滤它自己的参数,例如

public @interface Exclude {
    JobType[] jobs;
    Color[] colors;
    Foo[] foos;
    Quux[] quuxes;
}

这将完成两件事:

  1. 让您可以轻松地为每种不同的过滤器类型执行不同的过滤行为。
  2. 通过将不同的参数分类到不同的组中,使 @Excludes 注释更易读。

Enum.name() 的 Javadoc说:

Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

我建议你试着告诉你公司的人阅读Open/Closed principle并解释为什么在这种情况下违反它会特别有害。

关于Java 注释 - 对象数组或 toString 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31244846/

相关文章:

Java 比较字符串

java - 类命名约定

asp.net - 将样式应用于 CheckBoxList 中的 ListItems

java - 为什么我不能返回数组的值?

java - 如何使用 Selenium Webdriver 在同一窗口中打开的多个选项卡(超过 2 个)之间切换

java - JSESSIONID 的值在 session 失效时不会更改

python - 在 Python 3.6 中运行时根据 Union 类型检查变量

java - 我如何能够更新集合中每个文档的值并使其随着每个文档而递增?

java - 嵌套异常是 java.lang.IllegalStateException : Cannot convert value of type [java. lang.String] 到所需类型

spring-mvc - Spring 注解中大括号中的值