Java essay (1) annotation (top) __java

Source: Internet
Author: User

Reprint Please note: http://blog.csdn.net/wjzj000/article/details/53227352


Personal GitHub on the two small open source projects, I hope that the big guys can support star. Https://github.com/zhiaixinyang/PersonalCollect (GitHub the excellent frame in one, all split away without any additional library imports)

HTTPS://GITHUB.COM/ZHIAIXINYANG/MYFIRSTAPP (RETROFIT+RXJAVA+MVP)



Let's start with a quick look at what annotations are: Simply say the annotations, and the annotations themselves have no effect. Simply saying and commenting are no different, and the reason it works is the annotation class. That is, the specific class that explains the annotations. Generally these classes use reflection to complete some of the annotations of the business.


Today, a demo of annotations is recorded, and the effect is to quickly generate SQL statements through annotations.

The first is the annotation class: Table,column (represented separately: tables and columns)


@Target (Elementtype.type)   
@Retention (retentionpolicy.runtime) public   
@interface Table {  
	String value () ;   
}   


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

@Target:
The annotation used to describe the scope of the annotation (that is, where the described annotation can be used) (annotation) can be used for packages, types (class, interface, enum, annotation type), type member (method, constructor, member variable, enumeration value), Method parameters and local variables (such as loop variables, catch parameters). Using target in a declaration of the annotation type can make the target more explicit.
VALUES (ElementType) are:
Elementtype.annotation_type can be applied to annotation types. Elementtype.constructor can be applied to constructors. Elementtype.field can be applied to fields or properties. Elementtype.local_variable can be applied to local variables. Elementtype.method can be applied to method-level annotations. Elementtype.package can be applied to package declarations. Elementtype.parameter can be applied to the parameters of a method. Elementtype.type can be applied to any element of a class.

@Retention:
@Retention defines the length of time that the annotation is retained: Some annotations appear only in the source code and are discarded by the compiler, while others are compiled in the class file; annotations compiled in the class file may be ignored by the virtual machine. Others will be read when class is loaded (note that it does not affect class execution because annotations are separated from class in use). Use this meta-annotation to limit the "lifecycle" of annotations.
Role: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the described annotation is valid)
VALUES (Retentionpoicy) are:
1.SOURCE: Valid in the source file (that is, source file retention)
2.CLASS: Valid in class file (that is, class reservation)

3.RUNTIME: Valid at run time (that is, run-time reservation)


@Documented:

A public API that describes other types of annotation should be used as a member of the annotated program, so it can be documented by tools such as Javadoc. Documented is a tagged annotation with no members.


@Inherited:

is a markup annotation @Inherited illustrates that a labeled type is inherited. If a annotation type using the @inherited modifier is used for a class, the annotation will be used for subclasses of that class. Note: When @inherited's retention is retentionpolicy.runtime, the reflection API enhances this inheritance. If we use Java.lang.reflect to query a annotation of a @inherited annotation type, the reflection code check expands to work: Check class and its parent class until the specified annotation type is found.




Ps:
When a solution has only one member, it is written as value (), and of course it is not an error.

If you do not set this by default, you must pass values when you use annotations

Only classes can be annotated because an interface or abstract class cannot be instantiated with the new operation; A class that is annotated must provide at least one public default constructor (that is, a constructor without parameters). No, we can't instantiate an object.
followed by the use of the annotation class: person (is a Java bean using annotations)

@Table (' person ') public
class Person {
	@Column ("name")
	private String name;
	@Column ("user_name")
	private String usename;
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	Public String Getusename () {return
		usename;
	}
	public void Setusename (String usename) {
		this.usename = usename;
	}
}

Ps:
If you have more than two parameters: you must use @column (value= "user_name")


The end is used in main ():
public static void Main (string[] args) {//TODO auto-generated A stub person p1=new person (); Sets the table name and column name.
		PS: Here's the variable name to get a little wonderful, everyone please disregard.
		P1.setname ("AI");
		
		P1.setusename ("Aiai");
		String Str=query (p1);
	System.out.println (str);
		public static String query (person person) {StringBuilder sb=new StringBuilder ();
		By reflection, get Class object class P=person.getclass ();
		Determine if this class is an annotation class Boolean exist=p.isannotationpresent (Table.class);
		if (!exist) {return null;
		//If yes, Force type conversion to table Table table= (table) p.getannotation (Table.class);
		String Tablename=table.value ();
		The next step is to fetch the value of the SQL statement and repeat the process.
		Sb.append ("SELECT * from"). Append (tablename). Append ("where 1=1");
		Field[] Farray=p.getdeclaredfields ();
			for (Field Field:farray) {boolean fexist=field.isannotationpresent (Column.class);
			if (!fexist) {return null;
			} Column column=field.getannotation (Column.class);
			String Cloumnname=column.value ();
			String Fieldname=field.getname (); Object Fieldvalue=null
			The Getxx method is generated here to perform the corresponding get method of the bottom through reflection to obtain the return value inside.
			String getmethodname= "Get" +fieldname.substring (0, 1). toUpperCase () +fieldname.substring (1);
				try {method Method=p.getmethod (getmethodname);
			Fieldvalue=method.invoke (person);
			catch (Exception e) {e.printstacktrace ();
		} sb.append ("and"). Append (Cloumnname). Append ("="). Append (Fieldvalue);
	return sb.tostring ();
 }



Ps:
It's probably no use writing like this. But if this is a library. Then we just need to follow the library requirements. Use the appropriate annotation to complete the annotation in a specific format. We can get the final result directly. For example, you can write a tool class in the library, call the tool class directly, pass the required parameters, return the final concatenation of the SQL statement, and no statement errors occur.

Think of it as a little bit of excitement.


Recently there is a combination of Butterknife wrote about the annotation of the comb, interested reader can go to hold a field:

http://blog.csdn.net/wjzj000/article/details/54177914



Operation Effect:


Finally, I hope you reader can star my GitHub, three knock on the nine worship, the ground roll to seek star:
Https://github.com/zhiaixinyang/PersonalCollect
Https://github.com/zhiaixinyang/MyFirstApp


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.