Java annotation learning and java annotation Learning
I have nothing to worry about over the weekend. I want to study the annotation knowledge. I have forgotten it several times before. I learned this time and wrote an article to record it,
1. Metadata Annotation
Meta annotation refers to the annotation of the annotation. There are four types: @ Retention @ Target @ Document @ Inherited.
1.1 @ Retention: defines the annotation Retention policy
Java code
Copy the Code as follows:
@ Retention (RetentionPolicy. SOURCE) // The annotation only exists in the SOURCE code and is not included in the class bytecode file.
@ Retention (RetentionPolicy. CLASS) // The default Retention policy. The annotation will exist in the class bytecode file, but cannot be obtained at runtime,
@ Retention (RetentionPolicy. RUNTIME) // The annotation will exist in the class bytecode file and can be obtained through reflection during RUNTIME.
1.2 @ Target: define the Target of the Annotation
Java code
Copy the Code as follows:
@ Target (ElementType. TYPE) // interface, class, enumeration, Annotation
@ Target (ElementType. FIELD) // constant of the FIELD and enumeration
@ Target (ElementType. METHOD) // METHOD
@ Target (ElementType. PARAMETER) // method PARAMETER
@ Target (ElementType. CONSTRUCTOR) // CONSTRUCTOR
@ Target (ElementType. LOCAL_VARIABLE) // local variable
@ Target (ElementType. ANNOTATION_TYPE) // Annotation
@ Target (ElementType. PACKAGE) // PACKAGE
There can be multiple elementtypes, and one annotation can be class, method, and field.
1.3 @ Document: indicates that the annotation will be included in javadoc.
1.4 @ Inherited: indicates that the subclass can inherit the annotation in the parent class.
2. annotation Customization
Java code
Copy the Code as follows:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface HelloWorld { public String name() default ""; }
3. Use of annotations and test classes
Java code
Copy the Code as follows:
Public class SayHello {@ HelloWorld (name = "James") public void sayHello (String name) {System. out. println (name + "say hello world! ");} // Www.heatpress123.net}
4. parse Annotation
The reflection mechanism of java can help to get annotations. The Code is as follows:
Java code
Copy the Code as follows:
Public class AnnTest {public void parseMethod (Class <?> Clazz) {Object obj; try {// create a new Object obj = clazz through the default constructor. getConstructor (new Class [] {}). newInstance (new Object [] {}); for (Method method: clazz. getDeclaredMethods () {HelloWorld say = method. getAnnotation (HelloWorld. class); String name = ""; if (say! = Null) {name = say. name (); System. out. println (name); method. invoke (obj, name) ;}} catch (Exception e) {e. printStackTrace () ;}} public static void main (String [] args) {AnnTest t = new AnnTest (); t. parseMethod (SayHello. class );}}
Let's look at a complex example of java programming. We'll review it again. He uses annotations to create a database.
First, write an annotation of the database name to read the Database Name:
package com.bin.annotation;import java.lang.annotation.*;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DBTable {public String name() default"";}
Create an integer field:
Package com. bin. annotation; 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 SQLInteger {String name () default ""; // The default value is null. Constraints constraints () default @ Constraints; // other type definitions of fields}
Create a String field:
package com.bin.annotation;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 SQLString {int value() default 0;String name() default "";Constraints constraints() default @Constraints;}
Some other definitions
package com.bin.annotation;import java.lang.annotation.*;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Constraints {boolean primaryKey() default false;boolean allowNull() default true;boolean unique() default false;}
Create an annotation bean
package com.bin.annotation;@DBTable(name="MEMBER")public class Member {@SQLString(30)String firstName;@SQLString(50) String lastName;@SQLInteger Integer age;@SQLString(value=30,constraints=@Constraints(primaryKey=true))String handle;static int memberCount;public String toString(){return handle.toString();}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;}}
Finally, let's parse this annotation:
package com.bin.annotation;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.List;public class TableCreator {public static void main(String[] args) throws ClassNotFoundException{Class<?> cl =Member.class;DBTable dbtalbe=cl.getAnnotation(DBTable.class);String tableName = dbtalbe.name();if(tableName.length() <1)tableName=cl.getName().toUpperCase();List<String> columnDefs = new ArrayList<String>();for(Field filed : cl.getDeclaredFields()){String columnName = null;Annotation[] anns = filed.getDeclaredAnnotations();if(anns.length < 1)continue;if(anns[0] instanceof SQLInteger){SQLInteger sInt = (SQLInteger)anns[0];if(sInt.name().length() < 1)columnName = filed.getName().toUpperCase();elsecolumnName = sInt.name();columnDefs.add(columnName + " INT " + getConstraints(sInt.constraints()));}if(anns[0] instanceof SQLString){SQLString sString =(SQLString) anns[0];if(sString.name().length() <1){columnName = filed.getName().toUpperCase();}elsecolumnName =sString.name();columnDefs.add(columnName + " VARCHAR("+sString.value()+") " +getConstraints(sString.constraints()));}}StringBuilder createCommand = new StringBuilder("CREATE TABLE" +tableName + "(");for(String columnDef : columnDefs)createCommand.append("\n "+columnDef+ ",");String tableCreate = createCommand.substring(0,createCommand.length()-1)+"\n );";System.out.print(tableCreate);}private static String getConstraints(Constraints con){String constraints = "";if(!con.allowNull()){constraints +="NOT NULL";}if(!con.primaryKey()){constraints +="PRIMARY KEY";}if(!con.unique()){constraints +="UNIQUE";}return constraints;}}
Learning materials for java annotations
I suggest you read two books. The annotations are very detailed. These two books are very useful on the Internet.
1. Thinking in Java)
2 Agile Java-Test-Driven Development programming technology (Agile Java-Crafting code with Test-Driven Development)
Java annotations are important. What help do I need to learn about later large-scale projects?
Let's take a look at it. But it's definitely not necessary to actually customize annotations.
Generally, you need to know a few common ones, such as override supposeWarning Depricated.
Many mainstream frameworks now provide plug-ins that support annotation. The effect is the same as that of xml, that is, the syntax is different. Now, some units like to use this plug-in. It is not difficult to change the xml syntax to change the configuration file. return to the class