在下面的文档中,详细介绍了 2009 年有关注释验证的研究,内容如下:
http://www.ii.uib.no/~federico/latex/annotationlimitations2.pdf
Let us point out that in practice it can be possible to annotate directly a field of an object as they do in [3]:
@IntRange(min=1,max=100000) private int Amount;
However we decided not to offer this possibility for a simple reason: if the field is private, the framework must first change its visibility to public by means of reflection, before to be able to retrieve its value. We consider a very bad practice to allow an external framework to tamper with the visibility of object properties.
因此,他们没有像上例那样将注释放在私有(private)变量声明上,而是将注释放在公共(public) getter() 方法上。
public class WebForm {
private int Amount;
...
@IntRange(min=1,max=100000)
public int getAmount {
return this.Amount;
}
}
这篇论文的日期是 2009 年,所以我想知道这仍然适用吗?如果我使用 Hibernate Validator,遵循 JSR-380 和 Bean Validation 2.0 规范,我是否需要在 getter 级别声明验证注释以避免私有(private)变量通过 Hibernate 框架的反射而公开? 我在网上看到的大多数/所有示例都没有这样做 - 他们很乐意将注释放在私有(private)变量声明之上。
最佳答案
使用反射来更改字段的可见性实际上不会更改该字段的可见性。它返回公共(public)字段的副本。不,这仍然不适用。
关于Java 注解公共(public)/私有(private)范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51561742/