Java 注解公共(public)/私有(private)范围

标签 java hibernate annotations hibernate-validator

在下面的文档中,详细介绍了 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/

相关文章:

java - 在rest API中应用@OrderBy注释而不是排序

java - Vector<> 类的 toArray() 方法

Java:renameTo() 函数失败

java - SpringBoot 2.0应用中src/main/resources/config/env/dev2下的文件: java. io.FileNotFoundException导致的错误

java - Spring 3 MVC Hibernate 3.5.4 hibernateTemplate 不关闭连接(非事务性)

java - Lombok 注释的优先级是什么?

java - 用于计算字符串匹配条件的 OQL 语法

hibernate - 如何在 HIbernate HQL 中选择对象的类?

java - StackOverflow 错误设置多对多关系 Spring JPA

Django 注释和 values() : extra field in 'group by' causes unexpected results