Java annotation usage and custom annotation Processor

Source: Internet
Author: User
Tags psql

Preface:

In J2EE, annotations make development more convenient, saving the process of generating XML files. In Hibernate object declaration, you can simply use several annotations to avoid generating an XML file. This article mainly discusses the usage of annotation and the custom annotation processing tool. Annotations can be used when a large amount of repetitive work is involved in creating descriptor classes or interfaces.

Basic Syntax:

Java currently includes three standard annotations and four meta annotations. The meta annotation is mainly used to annotate other annotations.

Three standard Annotations:

@ Override indicates that the current method definition overwrites the methods in the parent class. You must have the same method signature (method name, parameter type, Parameter order, and number of parameters. Otherwise, an error message is sent during compilation.

@ Deprecated: Add annotations to methods that should not be used. When this method is used, a prompt is displayed during compilation.

@ SuppressWarnings: Disable improper compiler alarm information

Four meta Annotations:

@ Target indicates where the annotation can be used.

Such as CONSTRUCTOR, CONSTRUCTOR Declaration; FIELD, FIELD Declaration; METHOD, METHOD declaration; TYPE, class, interface or enum Declaration

@ Retention indicates the level at which the annotation information needs to be saved.

For example, for SOURCE, the annotation will be discarded by the compiler; for CLASS, the annotation is available in the class file, but it will be discarded by the VM.

RUNTIME, the VM will also retain the annotation during RUNTIME, And the annotation information can be read using the reflection mechanism.

@ Brief ented: Include this annotation in Javadoc.

@ Inherited: Allows subclass to inherit the annotation of the parent class.

Definition annotation:

The custom annotation is marked by @ interface. Like an interface definition, each method name defined here is the element name when the annotation is used, and the return value of the method is the element type. You can use default to declare the default value, however, for non-basic types, null cannot be set as the default value. Generally, null strings are used as the default value for strings.

As follows:


Package whut. annotation; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; // define an annotation @ Target (ElementType. METHOD) // defines where the annotation will be applied, the METHOD or domain @ Retention (RetentionPolicy. RUNTIME) // defines the level at which the annotation can be set to public @ interface UseCase {// annotation element. You can specify the default value. When using annotations, you can directly assign values to an element, such as id = 5 public int id (); public String description () default "no description"; // you can use enumeration to set the parameter type public enum ParameterType {STRING, SHORT, INT, BOOL, LONG, OBJECT}; // default value. When using annotations, you only need to assign public ParameterType () default ParameterType to the element. STRING ;}

Note:

Directly @ annotation name before any domain value in the class or before the method, for example @ UseCaseid = 5), during the annotation process, you must assign values to elements that do not have default values. assign values to each element by name-value pair. If there is an element named value in the annotation definition and it is unique and requires a value assignment, you can directly give the value required by value in brackets.

Annotations cannot be inherited.

The following is a basic annotation processor model implemented using non-apt.

This model can annotate entities for database ing and table creation. Is the most basic operation.

Annotation definition: The four annotation names are in different files.

Package whut. annotationDB; 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) // define the constraint of the field public @ interface Constraints {boolean primaryKey () default false; boolean allowNull () default true; boolean unique () default false ;} /// // package whut. annotationDB; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target (ElementType. TYPE) // class, interface or enum @ Retention (RetentionPolicy. RUNTIME) // define the table name annotation public @ interface DBTable {public String name () default "";} /// // package whut. annotationDB; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target (ElementType. FIELD) // class, interface or enum @ Retention (RetentionPolicy. RUNTIME) public @ interface SQLInteger {String name () default ""; // nested annotation function, embedding column-type database constraint information into Constraints constraints () default @ Constraints ;} /// // package whut. annotationDB; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target (ElementType. FIELD) // class, interface or enum @ Retention (RetentionPolicy. RUNTIME) public @ interface SQLString {int value () default 0; String name () default ""; // reference other annotations in the annotation element, Constraints constraints () default @ Constraints ;}

Object annotation: The RUNTIME annotation is used here, So RetentionPolicy. RUNTIME

Package whut. annotationDB; @ DBTable (name = "MEMBER") public class Member {// when using annotation, if the element is value and only value needs to be assigned, // write the value to @ SQLString (30) private String firstName in (); @ SQLString (50) private String lastName; @ SQLInteger private Integer age; @ SQLString (value = 30, constraints = @ Constraints (primaryKey = true) private String handle; public String getFirstName () {return firstName;} public void setFirstName (String firstName) {this. firstName = firstName;} public String getLastName () {return lastName;} public void setLastName (String lastName) {this. lastName = lastName;} public Integer getAge () {return age;} public void setAge (Integer age) {this. age = age;} public String getHandle () {return handle;} public void setHandle (String handle) {this. handle = handle ;}}

Specific annotation processors not implemented by apt:

Package whut. annotationDB; import java. lang. annotation. annotation; import java. lang. reflect. field; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. SQLException; import java. util. arrayList; import java. util. list; public class TableCreator {public Connection getConnection () {String user = "root"; String password = ""; String serverUrl = "jdbc: mys Ql: // localhost: 3306/carrent? User = root & password = "; try {Class. forName ("com. mysql. jdbc. driver "); Connection con = DriverManager. getConnection (serverUrl, user, password); return con;} catch (Exception e) {e. printStackTrace (); return null ;}// implement the public static void main (String [] args) {TableCreator tc = new TableCreator (); tc.exe cuteCreateDB (Member. class);} public void executeCreateDB (Class <?> Entity) {String sqlStr = explainAnnotation (entity); Connection con = getConnection (); PreparedStatement psql = null; if (con! = Null &&! SqlStr. equals ("error") {try {psql = con. prepareStatement (sqlStr); psql.exe cute ();} catch (SQLException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} finally {try {if (psql! = Null) psql. close () ;}catch (SQLException e) {e. printStackTrace () ;}try {if (con! = Null) psql. close ();} catch (SQLException e) {e. printStackTrace () ;}} else System. out. println ("failure... ") ;}// real processor, Class <?> Public String explainAnnotation (Class <?> Entity) {// obtain the annotation DBTable dbtable = entity of the specified type. getAnnotation (DBTable. class); if (dbtable = null) {System. out. println ("No DBTable annotation in class" + entity. getName (); return "error";} else {String tableName = dbtable. name (); // obtain the annotation name value, that is, the table name. // if the name value is not set, use the class name as the table name if (tableName. length () <1) tableName = entity. getName (). toUpperCase (); // convert the value in uppercase // prepare to process the field annotation List <String> columnsDefs = new RrayList <String> (); // obtain all fields of the class for (Field field: entity. getDeclaredFields () {String columnName = null; // obtain all annotations for this field Annotation [] anns = field. getDeclaredAnnotations (); // Annotation [] anns = field. getAnnotations (); // if (anns. length> = 1) {// determine the annotation type if (anns [0] instanceof SQLInteger) {SQLInteger sInt = (SQLInteger) anns [0]; // when no name exists, the field is capitalized as the column name if (sInt. name (). length () <1) column Name = field. getName (). toUpperCase (); else columnName = sInt. name (); columnsDefs. add (columnName + "INT" + getConstraints (sInt. constraints ();} if (anns [0] instanceof SQLString) {SQLString sString = (SQLString) anns [0]; // when no name exists, the field is capitalized as the column name if (sString. name (). length () <1) columnName = field. getName (). toUpperCase (); else columnName = sString. name (); columnsDefs. add (columnName + "VARCHAR (" + s String. value () + ")" + getConstraints (sString. constraints () ;}} StringBuilder createDB = new StringBuilder ("create table" + tableName + "("); for (String cols: columnsDefs) createDB. append ("" + cols + ","); // remove the last one, no. String tableSQL = createDB. substring (0, createDB. length ()-1) + ");"; // output the table creation process System. out. println ("Table Creation SQL is: \ n" + tableSQL); return tableSQL ;}// return the specified Constraint Public String getConstraints (Constraints con) {String constras = ""; if (! Con. allowNull () constras + = "not null"; if (con. primaryKey () constras + = "primary key"; if (con. unique () constras + = "UNIQUE"; return constras ;}}





This article from the "dream in the cloud" blog, please be sure to keep this source http://computerdragon.blog.51cto.com/6235984/1210969

Related Article

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.