Full parsing annotations

Source: Internet
Author: User
Tags deprecated

Why learn annotations, what are the benefits of learning annotations, and what can you do after learning?

1, be able to read the code written by others, especially the relevant code in the framework.

2, make programming more concise, code clearer

Concept self Baidu

Common annotations in Java

~ Common annotations (JDK annotations)

      

package annotations; public interface Person {public String name ();p ublic int Age (); @Deprecated//indicates that the method in this class is obsolete public void sing ();} package annotations; public class child implements person{@Overridepublic String name () {//TODO auto-generated method Stubreturn nu ll;} @Overridepublic int Age () {//TODO auto-generated method Stubreturn 0;} @Overridepublic void Sing () {//TODO auto-generated method stub}}package annotation; public class Maintest {@SuppressWarnings ("dep Recation ") public void Sing () {person p = new Child ();//Although this method is outdated, but I want to use this method, I will add the annotation p.sing ();} public static void Main (string[] args) {}}

Common third-party annotations

Annotations in ~spring {@Autowired, @Service, @Repository}; Annotations in MyBatis {@InsertProvider, @UpdateProvider, @Options};

        

public class Usermangerimpl implements usermanger{    private Userdao Userdao;    public void Setuserdao (Userdao userdao) {            This.userdao = Userdao;    }}    Configuring//configuration files with XML files <bean id= "Usermangerimpl" class= "Com.ss.spring.annotion.service.UserMangerImpl" >       < Property Name= "Userdao" ref= "Userdao"/></bean><bean id= "Userdao" class= " Com.ss.spring.annotion.persistence.UserMangerDaoImpl ">       <property name=" sessionfactory "ref=" Mysessionfactory "/></bean>//annotation introduced Autowiredpublic class Usermangerimpl implements usermanger{      @ autowired      private Userdao Userdao;    }  

~ Annotation Classification

SOURCE annotations

compiling annotations

Run annotations

~ Custom Annotations

Grammar:

@Target ({elementtype.method,elementtype.type}) @Retention (Retentionpolicy.runtime)//life cycle @inherited// Allow subclasses to inherit @documented//generate Javadoc with annotation information public @interface description{     string desc ();//Member no argument no exception declaration mode     string Author ()     int age () default 18;//can specify a default value for a member with default  }

When defining annotations, the member types are restricted and the valid types have primitive types and string,class,annotation,enumeration.

If the annotation has only one member, the name of the member must be named value (), and the member name and copy number (=) can be ignored when used.

Syntax for using annotations:

@< annotation Name > (< member name 1>=< member value 1>,< member name 2>=< member value 2>)

For example: @Description (desc= "I Am Tom", author= "Boy", age=18)

Public String Eyecolor () {

return "Red";

}

~ Parsing annotations

package annotation; import Java.lang.annotation.annotation;import Java.lang.reflect.method;public class Parse {public static void main (string[] args) {//1 use ClassLoader to load class try {Class C = Class.forn Ame ("annotations. Child ")//2 find the annotation above the class Boolean isexit = C.isannotationpresent (Description.class), if (isexit) {//3 Get the annotation instance Description Description = (description) c.getannotation (description.class); System.out.println (description);} Find the annotation on the method method[] ms = C.getmethods (); for (method M:ms) {Boolean ismethodexit = M.isannotationpresent ( Description.class); if (ismethodexit) {//3 Gets the annotation instance Description Description = (Description) m.getannotation ( Description.class); System.out.println (description);}} Another parsing method for (method M:ms) {annotation[] as = M.getannotations (), for (Annotation a:as) {if (a instanceof Description) {Des Cription Description = (description) A; System.out.println (Description.value ());}}} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} 

Inherited tests

Package annotations, @Description ("I am Interfacer") public class Person {@Description ("I Am Interface method") public String name () { return null;} public int Age () {return 0;} @Deprecated//Indicates that the method in this class is obsolete public void sing () {}}package annotation; public class child extends Person{public String name () {//TOD O auto-generated method Stubreturn null;} @Overridepublic int Age () {//TODO auto-generated method Stubreturn 0;} @Overridepublic void Sing () {//TODO auto-generated method stub}}package annotation; import java.lang.annotation.Annotation; Import Java.lang.reflect.method;public class Parse {public static void main (string[] args) {//1 use ClassLoader to load class try {Class C = Cla Ss.forname ("annotations. Child ")//2 find the annotation above the class Boolean isexit = C.isannotationpresent (Description.class), if (isexit) {//3 Get the annotation instance Description Description = (description) c.getannotation (description.class); System.out.println (description);} Find the annotation on the method method[] ms = C.getmethods (); for (method M:ms) {Boolean ismethodexit = M.isannotationpresent ( Description.class), if (ismethodexit) {//3 Gets the annotation realExample Description Description = (description) m.getannotation (description.class); System.out.println (description);}} Another parsing method for (method M:ms) {annotation[] as = M.getannotations (), for (Annotation a:as) {if (a instanceof Description) {Des Cription Description = (description) A; System.out.println (Description.value ());}}} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Result: @ annotation. Description (Value=i am interfacer)

* Annotated Combat

Requirements: There is a user table, the field includes the user ID, user name, nickname, age, Gender, city, mailbox, mobile number

Easily retrieve and print SQL for each field or field combination condition.

Package Com.zifeng.bean;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.Target; @Target ({elementtype.type}) @Retention ( retentionpolicy.runtime) public @interface Table {String value ();} Package Com.zifeng.bean;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.Target; @Target ({Elementtype.field}) @Retention ( retentionpolicy.runtime) public @interface Column {String value ();} Package Com.zifeng.bean, @Table ("User") public class Filter {@Column ("id") private int id; @Column ("user_name") private string userName; @Column ("User_nick") private String nickname; @Column ("Age") private int age; @Column ("user_city") private String city, @Column ("User_email") private string email, @Column ("User_monile") private string Mobile;public int GetId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String Getnickname () {return nickname;} public void Setnickname (String nickname) {this.nickname = nickname;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String getcity () {return city;} public void Setcity (String city) {this.city = city;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} Public String Getmobile () {return mobile;} public void Setmobile (String mobile) {this.mobile = mobile;} @Overridepublic String toString () {StringBuilder builder = new StringBuilder (); Builder.append ("Filter [id="); Builder.append (ID); Builder.append (", username="); Builder.append (userName); Builder.append (", nickname="); Builder.append (nickname), Builder.append (", age="), Builder.append (age), Builder.append (", city="); Builder.append ( City), Builder.append (", email="), builder.append (email), Builder.append (", mobile="); Builder.append (mobile); BuiLder.append ("]"); return builder.tostring ();}} Package Com.zifeng.bean;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;public class Test {public static void main (string[] args) {Filter f1 = new Filter (); F1.setid (8); /query user with ID 8 filter F2 = new filter (); F2.setusername ("Tom"); Filter F3 = new Filter (); F3.setemail ("[email protected]"); String sql1 = query (F1); String sql2 = query (F2); String sql3 = Query (F3); System.out.println (SQL1); System.out.println (SQL2); System.out.println (SQL3);} private static String query (Filter f) {StringBuffer SB = new StringBuffer ();//gets Classclass c = f.getclass ();//Gets the name of the table Bo Olean exists = c.isannotationpresent (Table.class), if (!exists) {return null;} Table T = (table) c.getannotation (Table.class); String tableName = T.value (); Sb.append ("Select * from"). Append (TableName). Append ("where 1=1");//Traverse all fields field[] Farray = C.getdeclaredfields (); for (field Field:farray) {//handles each field corresponding to the sql//to get the name of the field Boolean fexsist = Field.isannotationpresent (Column.class); if (!fexsist) {continue;} Column column = Field.getannotation (column.class); String columnName = Column.value ();//Gets the value of the field Object fieldvalue = ""; String filedname = Field.getname (); String getmethodname = "Get" +filedname.substring (0,1). toUpperCase () +filedname.substring (1); try {Method GetMethod =     C.getmethod (Getmethodname); Fieldvalue = (Object) getmethod.invoke (f);} catch (Exception e) {e.printstacktrace ();}//Stitching sqlif (Fieldvalue = = NULL | | (Fieldvalue instanceof integer && (integer) Fieldvalue = = 0)) {continue;} Sb.append ("and"). Append (Filedname); if (Fieldvalue instanceof String) {if ((String) fieldvalue). Contains (",")) { String[] values = (string) fieldvalue. Split (","); Sb.append ("In ("); for (string v:values) {sb.append ("'"); Sb.append (v ). Append ("'"). Append (",");} Sb.deletecharat (Sb.length ()-1); Sb.append (")");} else {sb.append ("="). Append ("'"). Append (Fieldvalue). Append ("'");}} else if (fieldvalue instanceof Integer) {sb.append ("=").Append (Fieldvalue);}} return sb.tostring ();}}

The result of the execution is:

SELECT * from user where 1=1 and id = 8
SELECT * from user where 1=1 and userName = ' Tom '
SELECT * from user where 1=1 and email = ' [email protected] '

It's easy to generate SQL statements with annotations, generate SQL statements for various tables, and you just need to change the bean entity.

  

  

Full parsing 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.