The annotation of Java and the secrets of the framework

Source: Internet
Author: User
Tags object object string format
When you use spring MVC or hibernate more than 3.0 versions, you may notice the convenience of annotation, but it often feels like annotation is really powerful, and that's a near-mistaken understanding. Annotation actually belongs to a kind of document annotation way, help us at compile time, run time, document generates when use, part of annotation actually basically and annotation is similar, here actually is to say the principle of annotation, and various functions on it how to realize, And what happens to him at the time of his inheritance.



Why is this. First of all, in my personal use of understanding, annotation is a subsidiary of class, type, attribute, parameter, local variable, method, constructor, package, annotation itself, and so on, which he relies on these elements, He does not have any role in itself, annotation's role is based on its attachment to these objects, according to the external program parsing caused his role, such as compile-time, in fact, the compile phase is running: Java Compiler, he will check these elements, For example: @SuppressWarnings, @Override, @Deprecated, and so on; the build document Run Javadoc is also a separate process to parse, in fact he is identifying the content, and spring MVC and hibernate annotations, The framework program in the runtime to parse these annotation, as for the initialization of the operation or when to be combined with the specific framework to see, today we have to say that the so-called annotation is how to achieve the function (again stressed: it itself does not function, functional and procedural decisions, He is just a few of the major elements described above, if he thinks he has the function, he never know what annotation is; we'll start by writing a annotation ourselves, writing annotation like writing a class, creating a Java file, and annotation's name is consistent, he will also generate class file, that he is also Java, but previously either interface, abstract class, class beginning, now more than a @interface, It is visible as a new object that the JVM can recognize, like a serialized interface tag, so let's write a simple one: The following code may look like you have no idea, and then down you may find interesting places: [Java] View plaincopy import Java.lang.annotation.ElementTypE  
Import java.lang.annotation.Retention;  
Import Java.lang.annotation.RetentionPolicy;  
Import Java.lang.annotation.Target; @Retention (Retentionpolicy.runtime) @Target ({elementtype.method, elementtype.constructor, Elementtype.field,  
Elementtype.type}) Public @interface newannotation {String value () default ""; So the above annotation representative: In runtime will be used (Retentionpolicy contains the other source, class level), can be annotated to methods, construction methods, properties, types and classes above



The name is: Newannotation, the inside has a property of value, is a string type, the default value is an empty string, that is, you can not pass parameters.  

   Use for example in A program: [Java] View plaincopy public class A {@NewAnnotation private String B;  
@NewAnnotation (value = "abc") public void Setb () {...} So a lot of people can see here and ask, what's the use of this writing?



It seems like there's no use, I didn't see it too much for the first time, and I saw what spring MVC was doing so versatile. In the framework of some projects, I've come up with a few features that, if there's a code accessory that will make the framework more beautiful and concise, and then think of Spring's stuff, Spring's AOP is based on bytecode enhancement, and the interceptor implementation is no longer a myth, So conversely, if annotation is resolvable, annotation injection is very straightforward, and hibernate is, of course, I'm not talking about some of the parsing caching issues, because it doesn't let each object parse once,


Will remember as much as possible to make the performance higher, here only to say that his principles. Here take a simple request object to convertFor the JavaBean object, if we use do as the suffix, some of the requested parameter names and actual properties are not the same (the general specification requirements are the same), followed by a network transmission in a project foreground date submitted to the background in milliseconds, but need to convert to the corresponding string format to deal with , the commit contains: String, int, Integer, long, long, string[] These types of data, we can expand the date, with these small requirements we have to write a simple: [Java] View plaincopy import  
Java.lang.annotation.ElementType;  
Import java.lang.annotation.Retention;  
Import Java.lang.annotation.RetentionPolicy;  


Import Java.lang.annotation.Target; @Retention (Retentionpolicy.runtime) @Target ({Elementtype.field}) public @interface reuqestannotation {String name ( Default "";//Incoming parameter name Boolean datestring () default false;//is datestring type} here annotation one is name one is datestring, two are

There is a default value, name we think is the parameter name in the request, otherwise directly to the property name, DateString property is a date string (the previous description of the passed date will become a millisecond value, so the need to automatically convert).   

  So let's write a Do: [Java] View plaincopy import Xxx.xxx.reuqestannotation;//import section Please refer to the public class Requesttemplatedo {  

  private String name;  

  @ReuqestAnnotation (name = "Myemail") private String email;  

  Private String desc; @ReuqestAnnotation (datestring = trUE) Private String inputdate;  

  Private Integer int1;  


  private int int2;  
  public int getInt1 () {return int1;  
 public int GetInt2 () {return int2;  
  Public String Getinputdate () {return inputdate;  
  Public String GetName () {return name;  
  Public String Getemail () {return email;  
  Public String GetDesc () {return desc; Note that the Set method is not written here, so instead of invoking the set method to illustrate the problem, we set the value directly with the attribute, which is a private setting, and the following is a conversion method: if there is a httputils, we write a static method: [Java  View Plaincopy/** * Get the corresponding object through request * @param <T> * @param request * @param clazz * @return * @throws illegalaccessexception * @throws instantiationexception/@SuppressWarnings ( "Unchecked") public static <t extends object> T Convertrequesttodo (httpservletrequest request, class<t> CLA ZZ) throws Instantiationexception, illegalaccessexception {Object object = clazz.newinstance ();  
     Field []fields = Clazz.getdeclaredfields ();  
     for (Field field:fields) {field.setaccessible (true);  
     String requestname = Field.getname ();  
     Reuqestannotation requestannotation = field.getannotation (Reuqestannotation.class);  
     Boolean isdatestring = false; if (requestannotation!= null) {if (Stringutils.isnotempty (Requestannotation.name ())) Requestname = Requestannotatio  
     N.name ();  
     isdatestring = Requestannotation.datestring ();  
     Class <?>clazzf = Field.gettype ();  
     if (Clazzf = = String.class) {if (isdatestring) {String datestr = Request.getparameter (requestname); if (datestr!= null) {Field.set (object, Datetimeutil.getdatetime (new Date (long.valueof), datestr  
     Ault_date_format));  
       }}else {Field.set (object, Request.getparameter (Requestname)); } else if (Clazzf = integer.class) field.set (objECT, Getinteger (Request.getparameter (requestname));  
     else if (Clazzf = = Int.class) Field.set (object, GetInt (Request.getparameter (requestname));  
     else if (Clazzf = = Long.class) Field.set (object, Getlongwapper (Request.getparameter (requestname));  
     else if (Clazzf = = Long.class) Field.setlong (object, Getlong (Request.getparameter (requestname));  
     else if (Clazzf = = String[].class) Field.set (object, Request.getparametervalues (Requestname));  
} return (T) object; This will be responsible for populating the corresponding values in the data, returning the corresponding do, which is used in the code: [Java] View plaincopy Requesttemplatedo Requesttemplatedo = httputils.c  
Onvertrequesttodo (Request, Requesttemplatedo.class); Note: This part of Spring has helped us write, but I'm talking about the general principle, and spring itself is different and more complete in this part, and it's just to illustrate the local problem. Spring can assemble this do after it is intercepted in the interceptor, so it can be passed directly into our business method in spring MVC, first known as the annotation of the business method, and after the method is determined by the URL, get the argument list, depending on the parameter type,



If it is the business do, then fill in the business do, hibernate can also be the same way to reason. OK, looks very simple, if you really feel simple, then this piece you really understand, then we say something special, is inherited, seemingly annotation rarely to inherit, but I met some friends of the project, due to part of the design needs or design flaws but do not want to modify the, you will find that most of the do most properties are the same, if you do not abstract the Father class out, if you modify the property to modify a lot of do at the same time, and the majority of the operation is the operation of these shared properties, so also want to use the back of the form to complete the code of universality and maintain polymorphism, at that time I was really blindfolded, Because it is based on a similar annotation framework, such as Hibernate, which later took a lot of tests with the problem and corresponded to the data, if annotation is not owned by the quilt class at the class level, the construction method level, That is, when subclasses pass XXX.class.getAnnotation (Xxxannotation.class), they are not available, but public-type methods, public properties, and, secondly, If a subclass overrides a property of the parent class or a method, regardless of whether the subclass has written annotation, all the annotation of the property or method of the parent class in the subclass is invalidated, that is, if the Father class has a property A, there are two annotation, if a is public,

Subclasses can inherit this property and annotation, and if subclasses also have a property of a, whether a is annotation or not, those annotation in the parent class will fail in the subclass. That's why I said annotation is a property, method, Package ... Accessory, which he was bound to on these elements, rather than having the actual function, when overridden, will be overwritten, the attribute, the method when is overwritten, its annotation also is covered with it, but does not follow the annotation to have a separate coverage; So then to solve that problem, I told him that the only way to use it was public, otherwise there was no way to use reflection, because hibernate could not find this field and didn't have the opportunity to provide a setaccessible, because the field was not visible at this time, However, these field can be seen through the parent class, as at the technical level, otherwise it is only the best way to modify the design.

Goto: http://blog.csdn.net/xieyuooo/article/details/8002321

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.