我需要编写一个注释,以从结果集中排除某些值。
背景:
从字段中选择不同的值,并在组合框中列出。一些旧式值已弃用,即使它们由JDBC的SELECT DISTINCT()
返回,我也不想显示它们。这就像一个小型框架,人们可以通过单击ComboBoxes中的值来构建选择查询。
我尝试了以下操作(代码无法编译-注释行是我尝试解决问题的方法):
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 ofEnum
.
不过,这是做您想要的最好的方法。这是东西:
Enum
类本身是没有意义的。仅在子类化时才有意义。假设您要添加另一个过滤器,例如
Color
(您自己的自定义Color
枚举,而不是java.awt.Color
)。显然,您的过滤类所做的事情与过滤出JobType
相比,过滤出Color
有很大不同!因此,最好的办法是让您尝试过滤的
enum
的每个不同时间都属于自己的参数,例如public @interface Exclude {
JobType[] jobs;
Color[] colors;
Foo[] foos;
Quux[] quuxes;
}
这将完成两件事:@Excludes
批注更易读。 Enum.name()
的Javadoc说:Returns the name of this
enum
constant, exactly as declared in itsenum
declaration. Most programmers should use thetoString()
method in preference to this one, as thetoString
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/