我需要编写一个注释来从结果集中排除某些值。
背景:
不同的值从字段中选择并列在组合框中。一些遗留值已弃用,我不想显示它们,即使它们由 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 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/