Java Custom Annotations

Source: Internet
Author: User
Tags deprecated

Reprint https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html

Brief introduction

Should this be a problem for many first-time contact developers? Annontation is a new feature introduced by Java5, the Chinese name is called annotation. It provides a secure, comment-like mechanism for associating any information or metadata (metadata) with program elements (classes, methods, member variables, and so on). Add a more intuitive and straightforward description of the program's Elements (classes, methods, member variables) that are not related to the business logic of the program and are intended for use by the specified tool or framework. Annontation, like a modifier, applies to a declaration statement for a package, type, constructor method, method, member variable, parameter, and local variable.
Java annotations are some of the meta-information that is attached to the code, used by some tools to parse and use at compile and run time, to illustrate and configure functionality. Annotations do not and do not affect the actual logic of the code, only the ancillary role. Included in the Java.lang.annotation package.

Common annotations

1.) Override
Java.lang.Override is a marker type annotation, which is used as a labeling method. It illustrates the way that the annotated method overloads the parent class and plays the role of the assertion. If we use this annotation in a method that does not overwrite the parent class method, the Java compiler warns with a compilation error.
2.) Deprecated
deprecated is also a marker type annotation. When a type or type member uses the @deprecated modifier, the compiler will not encourage the use of this annotated program element. So using this modification has a certain "continuity": if we use this obsolete type or member in the code by inheriting or overwriting it, although the inherited or overwritten type or member is not declared as @deprecated, the compiler still has to call the police.
3.) suppresswarnings
suppresswarning is not a marker type annotation. It has a member of type string[], and the value of this member is the forbidden warning name. For the Javac compiler, the warning name that is valid by the-xlint option is also valid for @suppresswarings, and the compiler ignores the unrecognized warning name.
@SuppressWarnings ("Unchecked")

Usefulness of annotations
    • Generate the document. This is the most common, and also the earliest annotations that Java provides. Commonly used have @param @return, etc.
    • Tracking code dependencies, implementing alternative profile features. For example, Dagger 2 dependency injection, the future Java development, will be a large number of annotations configuration, has great use;
    • A format check is made at compile time. such as @override before the method, if you do not override the method of the superclass method, compile time can be checked out.
The principle of annotations

The annotation essence is a special interface that inherits the annotation, and its concrete implementation class is the dynamic proxy class generated by Java runtime. When we get annotations through reflection, we return the dynamic proxy object $proxy1 generated by the Java runtime. Invoking a custom annotation (interface) method through a proxy object eventually calls the Annotationinvocationhandler invoke method. The method will index the corresponding value from the map of Membervalues. The source of Membervalues is the Java constant pool.

Meta annotations

Java.lang.annotation provides four types of meta-annotations that specifically annotate other annotations (you need to use the meta-annotations when customizing annotations):
@Documented – whether the annotations will be included in the Javadoc
@Retention – When to use this annotation
@Target – where the annotations are used
@Inherited – whether subclasses are allowed to inherit the annotation

1.) @Retention – Define the life cycle of the annotation
Retentionpolicy.source: Discarded during the compile phase. These annotations no longer have any meaning after compilation, so they do not write to bytecode. @Override, @SuppressWarnings all belong to this kind of annotation.
Retentionpolicy.class: Discarded when the class is loaded. Useful in the processing of bytecode files. Annotations are used this way by default
Retentionpolicy.runtime: It is never discarded and the runtime retains the annotation, so you can use the reflection mechanism to read information about the annotation. Our custom annotations are typically used this way.

2.) target– indicates where the annotation is used. The default value is any element that indicates where the annotation is used. The available ElementType parameters include
Elementtype.constructor: Used to describe the constructor
Elementtype.field: Member variables, objects, attributes (including enum instances)
Elementtype.local_variable: Used to describe local variables
Elementtype.method: Used to describe a method
Elementtype.package: Used to describe the package
Elementtype.parameter: Used to describe parameters
Elementtype.type: Used to describe classes, interfaces (including annotation types), or enum declarations

3.) @Documented – A simple annotations tag annotation that indicates whether the annotation information is added to the Java document.

4.) @Inherited – Define the relationship between the annotation and the subclass
@Inherited meta-annotation is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. If a annotation type that uses the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

Custom annotations
some rules written by custom annotation classes:1.  The annotation type is defined as @interface, and all annotation automatically inherit the Java.lang.Annotation interface and can no longer inherit other classes or interfaces. 2. Parameter members can be used only with public or by default (defaultthese two access rights modifiers3. Parameter members can only use the base type Byte, Short,Char,int,Long,float,Double, Boolean eight basic data types and data types such as String, Enum, Class, annotations, and these types of arrays. 4to get the annotation information for a class method and a field, you must get the annotation object through the Java reflection technique, because you have no other way to get the annotation object.5annotations can also have no members defined, but there's no use for annotations. PS: Custom annotations need to use meta annotations
Example
@Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented  public @Interface  fruitcategory {    default "";}
@Retention (retentionpolicy.runtime) @Target (Elementtype.field) @Documented  public @Interface  fruitcolor {    publicenum  color{blue,red, GREEN};     default Color.green;}
@Target (Elementtype.field) @Documented @retention (retentionpolicy.runtime)  public @Interface  fruitname {    default "";}
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documented  public @Interface  fruitprovider {    publicintdefault -1 ;      Public default "";      Public default "";}
 Packageannotation; @FruitCategory (value= "Fruit") Public classApple {@FruitName ("Apple")    PrivateString Applename; @FruitColor (Fruitcolor=FruitColor.Color.RED)PrivateString AppleColor; @FruitProvider (ID=1,name= "Shaanxi Red Fuji Group", address= "Red Fuji Building, No. 89th Yan an LU, Xi ' an, Shaanxi province")    PrivateString Appleprovider;  Public voidSetapplecolor (String applecolor) { This. AppleColor =AppleColor; }     PublicString Getapplecolor () {returnAppleColor; }     Public voidsetapplename (String applename) { This. Applename =Applename; }     PublicString Getapplename () {returnApplename; }     Public voidSetappleprovider (String appleprovider) { This. Appleprovider =Appleprovider; }     PublicString Getappleprovider () {returnAppleprovider; }}

Test

 Packageannotation;ImportJava.lang.reflect.Field; Public classFruitinfoutil { Public Static voidGetfruitinfo (class<?>clazz) {String Strfruitname= "Fruit Name:"; String Strfruitcolor= "Fruit Color:"; String Strfruitprovicer= "Supplier Information:"; Fruitcategory fruitcategory= Clazz.getannotation (fruitcategory.class); System.out.println ("Category:" +Fruitcategory.value ()); Field[] Fields=Clazz.getdeclaredfields ();  for(Field field:fields) {if(Field.isannotationpresent (Fruitname.class) {fruitname Fruitname= (fruitname) field.getannotation (fruitname.class); Strfruitname=strfruitname+Fruitname.value ();            System.out.println (Strfruitname); }            Else if(Field.isannotationpresent (Fruitcolor.class) {Fruitcolor Fruitcolor= (Fruitcolor) field.getannotation (Fruitcolor.class); Strfruitcolor=strfruitcolor+Fruitcolor.fruitcolor (). toString ();            System.out.println (Strfruitcolor); }            Else if(Field.isannotationpresent (Fruitprovider.class) {Fruitprovider Fruitprovider= (Fruitprovider) field.getannotation (Fruitprovider.class); Strfruitprovicer= "Vendor Number:" +fruitprovider.id () + "supplier Name:" +fruitprovider.name () + "supplier Address:" +fruitprovider.address ();            System.out.println (Strfruitprovicer); }        }    }     Public Static voidMain (string[] args) {fruitinfoutil.getfruitinfo (Apple.class); }}

Output

Category: Fruit fruit name: Apple fruit color: Red Vendor ID:1 supplier Name: Shaanxi Red Fuji Group supplier Address: Red Fuji Building, No. 89th Yan an LU, Xi ' an, Shaanxi province

Java Custom Annotations

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.