java--annotations

Source: Internet
Author: User

I. Basic of annotations

1. Popular understanding of annotations

Annotations (Annotation) provide a formalized way for us to add information to our code, which we can use at a later time (by parsing annotations to use the data).

2. The role of annotations

    • Generate document
    • Track code dependencies, implement alternative profile features, and reduce configuration. As some annotations in spring
    • Format checking at compile time, such as @override, etc.
    • Whenever you create a class or interface with descriptor properties, you can consider using annotations to simplify and automate the process once it contains repetitive work.

3. Status of annotations

SOURCE annotations: Annotations that exist only in the source code.

Compile-time annotations: annotations exist in both the source code and the. class file.

Runtime Annotations: The run phase also works, even annotations that affect the running logic, such as those commonly used in spring, mybatic.

4. Classification of annotations

A.JDK built-in annotations:

    • @Override: indicates that the current method definition overrides the method in the superclass, and if an error occurs, the compiler will error.
    • @Deprecated: If you use this annotation, the compiler will receive a warning message.
    • @SuppressWarnings: ignores compiler warning messages.

As an example of override, the other method self-test, child inherits the person, and overrides the method in person:

 Public classChildextendsPerson {@Override//cover     Public intAge () {//TODO auto-generated Method Stub        return0; } @Override PublicString name () {//TODO auto-generated Method Stub        return NULL; } @Override Public voidSing () {//TODO auto-generated Method Stub            }}

B. Meta-annotations

Annotations, 4 Common, are used in custom annotations, respectively

@Target, @Retention, @Documented, @Inherited

C. Custom annotations

Self-defined annotations. Custom annotations consist of meta-annotations and their own defined annotations (annotation), with the following formats, requirements, and examples:

    //Custom Annotations//The following 4 lines are meta annotations@Target ({elementtype.method,elementtype.type}) @Retention (Retentionpolicy.source)//Scope of meta-annotations, life cycle@Inherited//Allow child inheritance@Documented//The Javadoc document is generated with a secondary annotation//defining annotations with the @interface keyword     Public@Interfacedescription{/** Member types are restricted, all basic types, String, Class, enum, Annotation, and arrays of the above types. * If the annotation has only one member, the member name must be named value (), * In use is can ignore member name and assignment name * Note Class can have no members, annotations without members are called identity annotations*/String value ();//member declared without argument or exception//String author (); //int age () default;//You can assign a default value to a member            }

5. Annotation parsing

Annotation parsing is actually using the reflection mechanism in Java, do not understand can see my previous blog, java--reflection of the gradual understanding

The core code is as follows:

//1. Loading classes with the class loader        Try{Class Class1=class.forname ("Cn.ann.test.child");
//2. Find the annotations above the class BooleanIsexist=class1.isannotationpresent (Description.class);//determine if this annotation existsMethod[] ms =Class1.getmethods (); for(Method method:ms) {BooleanExist=method.isannotationpresent (Description.class); if(exist) {Description B= (Description) method.getannotation (Description.class); System.out.println (B.value ()); } } if(isexist) {//3. Need to get an example of annotationsDescription a= (Description) class1.getannotation (Description.class); System.out.println (A.value ()); } //4. Find the annotations on the method for(Method method:ms) {annotation[] s=method.getannotations (); for(Annotation annotation:s) {if(AnnotationinstanceofDescription) {System.out.println (((Description) annotation). value ()); } } } } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }

Two. A small scene of the annotation application

1. Scenario Requirements

A. There is a user table with fields including user ID, username, nickname, age, City

B. Easily retrieve the combined conditions of each field or field and print out the SQL

2. Implementation methods

The code is as follows (which comments the idea of the code):

A. User table Users.java

@Table ("User") Public classUsers {@Column ("id")    Private intID; @Column ("User_name")    PrivateString UserName; @Column ("Nick_name")    PrivateString Nickname; @Column ("Age")    Private intAge ; @Column ("City")    PrivateString City;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }     PublicString Getnickname () {returnnickname; }     Public voidSetnickname (String nickname) { This. Nickname =nickname; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString getcity () {returnCity ; }     Public voidsetcity (String city) { This. City =City ; }}

B. Custom Annotations Table.java

@Target ({elementtype.type}) @Retention (retentionpolicy.runtime) @Inherited @documented  public @Interface  Table {    String value ();}

C. Custom Annotations Column.java

@Target ({Elementtype.field}) @Retention (retentionpolicy.runtime) @Inherited @documented  public @Interface  Column {    String value ();}

D. Test class Test.java

 Public classTest { Public Static voidMain (string[] args) { Users F1=New Users(); F1.setid (68);//represents a user with a query ID of 68F1.setage (35);
Users F2=NewUsers (); F2.setusername ("Huhu"); F2.setcity ("Lanzhou");

Users f3 =New Users(); F3.setage (20);
String SQL1=query (F1); String SQL2=query (F2); String Sql3=query (F3);
System.out.println (SQL1); System.out.println (SQL2); System.out.println (SQL3); } @SuppressWarnings ("Unchecked") Public StaticString query (Object obj) {StringBuilder s=NewStringBuilder (); //1. Get to ClassClass Class1 =Obj.getclass (); //2. Get the name of the table BooleanIsexist = Class1.isannotationpresent (Table.class); if(isexist) {Table htable= (table) class1.getannotation (table).class); S.append ("SELECT * from"). Append (Htable.value ()). Append ("Where 1=1"); } //3. Iterate through all the fieldsfield[] Fields =Class1.getdeclaredfields (); for(Field field:fields) {Booleanexist = Field.isannotationpresent (Column.class); if(exist) {Column F= (column) field.getannotation (column).class); String ColumnName=F.value (); //System.out.println (columnName);String FieldName =Field.getname (); Object fieldstring=NULL; String Getmethodname= "Get" +fieldname.substring (0,1). toUpperCase () +fieldname.substring (1); Try { /** 4. Handle each field corresponding to SQL * 4.1 get field name * 4.2 Get field value * 4.3 Assemble sql */Method Amethod=Class1.getmethod (getmethodname); Fieldstring= (Object) amethod.invoke (obj,NULL); //System.out.println (fieldstring); if(fieldstring==NULL|| (fieldstringinstanceofInteger && (integer) fieldstring==0)){ Continue; } s.append ("and" +columnName); if(fieldstringinstanceofString) {S.append ("=" + "'" "+fieldstring+" "); } Else{s.append (" = "+fieldstring); } } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(nosuchmethodexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } //method[] msmethods = Class1.getmethods (); //For (Method method:msmethods) {//Method.invoke (Class1, Object); //} returns.tostring (); }}

Three. A picture describes the annotations

Thank you for reading.

java--annotations

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.