如何检查注释的相等性?
您将如何实现此方法:
public boolean equal(Annotation a1, Annotation a2) {
...
}
示例输入 ():
@First(name="1", value="1"), @Second(name="1", value="1")
@First(value="2"), @First(name="2")
@First(value="3"), @First(value="3")
@Second(name="4", value="4), @Second(name="4", value="4")
示例输出:
false
false
true
true
如您所见,equal
的预期行为很清晰,并且与标准 equals
方法的预期行为类似java中的常规对象(问题是我们不能覆盖注释的equals
)。
是否有任何库或标准实现?
How would you implement this method:
public boolean equal(Annotation a1, Annotation a2) {
...
}
Sample input ():
@First(name="1", value="1"), @Second(name="1", value="1")
@First(value="2"), @First(name="2")
@First(value="3"), @First(value="3")
@Second(name="4", value="4), @Second(name="4", value="4")
Sample output:
false
false
true
true
As you can see, the expected behavior of equal
is clear and similar to expected behavior of standard equals
method of regular objects in java (the problem is that we cannot override equals
for annotations).
Are there any libs or standard implementations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是 重写等于用于
注释
工作?也许我不明白你的问题。Doesn't the overriden equals for
Annotation
work? Maybe I don't understand your question.如果你想检查a1和a2是否是同一个注释。试试这个:
a1.annotationType().equals(a2.annotationType())
If you want to check whether a1 and a2 are the same annotation. Try this:
a1.annotationType().equals(a2.annotationType())
我的答案中令人烦恼的部分是我无法扩展自定义注释(在继承的意义上)。这会简化 equals 方法。
First.java
Second.java
Thing1.java
Example.java
注意: 我没有引入在 First 和 Second(自定义注释)中使用的 NamePairValue 持有者,因为这与“示例输入( ):“完全正确!
有关此样式/解决方案的详细信息,请参阅此堆栈跟踪。
如何扩展Java注释?
这个问题已经有10年历史了,但问题没有得到解答正如罗曼所问。凭借 4k 观看次数,我希望这对某人有帮助!
The annoying part of my answer is I can not extend a custom annotation (in the sense of inheritance). That would have simplified the equals method.
First.java
Second.java
Thing1.java
Example.java
Note: I did not introduce a NamePairValue holder to use within First, and Second (custom annotation) because this didn't match the "sample input():" exactly!
See this Stack Trace for details for this style / solution.
How to extend Java annotation?
This question is 10 years old but the question was not answered as asked by Roman. With 4k views, I hope this helps someone!!