简体   繁体   中英

Java Annotations public/private scope

In the following document, detailing a study from 2009 regarding annotation validations, the following is stated:

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.

So instead of putting the annotation on the private variable declaration as in the above example, they put the annotation on the public getter() method instead.

public class WebForm {
   private int Amount;
   ...
   @IntRange(min=1,max=100000)
   public int getAmount {
       return this.Amount;
   }
}

This paper is dated 2009, so I'm wondering does this still apply? If I am using the Hibernate Validator, following JSR-380 & the Bean Validation 2.0 specification, do I need to declare validation annotations at the getter level to avoid the private variable being made public by reflection by the Hibernate framework? Most/All of the examples I see online do not do this - they are happy to put the annotation above the private variable declaration.

Using reflection to change the visibility of a field doesn't actually change the visibility of that field. It returns a copy of the field that is public. No this does still not apply.

This paper never applied to Hibernate Validator and Bean Validation. We support annotations on private fields and we use reflection to access the content of the field.

Indeed we do that by making the field accessible to our code. This does not change the visibility of the field itself though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM