annotaion annotation Detailed case

Source: Internet
Author: User

1. Getting Started with annotations

2. Built-in annotations

3. Custom annotations, meta annotations

4, small case (use reflection to read the information of annotations, simulation process of processing annotation information)


1. Getting Started with annotations


Annotation is a new technology introduced from JDK5.0.

The role of annotation:

is not the program itself, you can interpret the program (in fact, it is very much like a comment) can be read by other programs (such as the compiler) (Annotation information processing process, is a significant difference between annotations and annotations, if there is no annotation information processing process, the annotations meaningless)

Format of annotation:

Annotations are present in the code with the "@ Comment name", and you can add some parameter values, such as suppresswarnings (value= "All")

Where to use annotation

Can be attached to the package, class, Mehod, field and so on, equivalent to add additional auxiliary information, we can use the reflection mechanism to achieve the access to these metadata


2. Built-in annotations


@Override

Defined in Java.lang.Override, this comment applies only to rhetorical methods, indicating that a method declaration intends to override another method declaration in a superclass

/* Copyright (C) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE proprietary/confidential. Use are subject to license terms. */package Java.lang;import java.lang.annotation.*;/** * Indicates that the purpose of the method declaration is to override * In the parent class method declaration. If a method is commented * This comment type compiler will generate an error * unless at least one of the following conditions is true: * * <ul><li> * Whether the method overrides or implements a method that is declared in a declaration * superclass. * </li><li> * The method has a signature with that equivalent * Any publicly declared method in {@linkplain Object}.  * </li></ul> * * @author  Peter von der ahé* @author  Joshua Bloch * @jls 9.6.1.4 Override * @since 1.5 */@Target (Elementtype.method) @Retention (retentionpolicy.source) public @interface Override {}

@Depercated

Defined in java.lang.Deprecated, this annotation user rhetoric methods, attributes, class representations discourage programmers from using such elements, usually because it is dangerous or there is a better choice


/* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * ORACLE proprietary/confidential. Use are subject to license terms. */package java.lang;import java.lang.annotation.*;import Static java.lang.annotation.elementtype.*;/** * @Deprecated <strong> </strong> program element annotations are used by a programmer * Do not use, usually because it is dangerous, * or because a better choice exists. Compiler Issue WARNING * Obsolete program elements use or override non-outdated code. * * @author  Neal gafter * @since 1.5 */@Documented @retention (retentionpolicy.runtime) @Target (Value={constructor, FIELD, local_variable, METHOD, Package, PARAMETER, TYPE}) public @interface Deprecated {}

@SuppressWarnings

Defined in java.lang.SuppressWarnings, used to suppress compile-time warning messages

/* * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. * ORACLE proprietary/confidential. Use are subject to license Terms. */package java.lang;import java.lang.annotation.*;import static Java.lang.annotation.elementtype.*;/** * indicates the element that will be named the compiler warning  * comment (and the  * element in all program elements included in the comment). Note that a set of warnings suppressed in a given element  * warning suppresses a superset of all contained elements. For  * For example, if you annotate a class to suppress a warning and comment  * method to suppress another, the two warnings will be suppressed by the method.  * * <p> as a style, programmers should often use this annotation  * in the deepest nested element, which is valid. If you want to  * suppress the warning in a particular method, you should annotate the  * method instead of its class.  * * @since 1.5 * @author Josh bloch */@Target ({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, Local_ VARIABLE}) @Retention (retentionpolicy.source) public @interface suppresswarnings {   /**      * Suppressed warning set in compiler      * annotation element. Duplicate names are allowed. Second      * names that appear consecutively are ignored. Presence      * Unrecognized warning name is not an error: The compiler must      * ignore any warning names that they do not recognize. However, they are,     * If a comment contains an unrecognized, free hairOut warning      * warning name.      *     * <p> compiler vendors should record their supported warning names      * used with this annotation type. Encourage them to cooperate      * ensure that the same name works on multiple compilers.      */    string[] value ();}


Use these built-in annotations

Package Com.lyy.test.annotion;import Java.util.arraylist;import Java.util.date;import java.util.List;@ Suppresswarnings ("All") public class Demo1/*extends object*/{@Overridepublic String toString () {return "";} @Deprecatedpublic static void <del>testoo1</del> () {System.out.println ("test.001");} public static void test002 () {List List = new arraylist<> ();} public static void Main (string[] args) {Date d = new Date ();<del>testoo1</del> ();}}



@SuppressWanings

Defined in java.lang.SuppressWarnings, to suppress the compile-time warning message is different from the first two comments, you need to add a parameter to use correctly, these parameter values are already defined, we use selectively


Parameter description

Deprecation warnings using outdated classes or methods

Unchecked A warning is performed for a check conversion, such as when using a collection without specifying a generic

FALLTHROUQH case penetration Occurs when a switch statement is used

Path has a warning that there are no paths in the classpath, source file path, etc.

Serial warning when a serialversionuid definition is missing on a serializable class

Finally , the warning when any filally clause cannot be completed

All warnings about all of these cases



3. Custom annotations and meta annotations

Automatically inherits the Java.lang.annotation.Annotation interface when you use @interface to customize annotations

Points:

@interface used to declare an annotation

Format: Public @interface annotation name (definition body)

Each of these methods is actually a reputation for a configuration parameter

The name of the method is the name of the parameter

The return value type is the type of the parameter (the return value type can only be base type, Class, String, enum)

You can declare the default value of a parameter through default

If there is only one parameter member, the general parameter is named value


Package com.lyy.test.annotion; @SxtMyAnnotationpublic class Demo2 {@SxtMyAnnotation (age=19,studentname= "bubble", id=1001 , schools={"Peking University", "Xiaogan College"}) public void Test () {} @SxtAnnotation2 ("1") public void Test2 () {}}


Package Com.lyy.test.annotion;import Java.lang.annotation.elementtype;import java.lang.annotation.Retention; Import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Target (Value={elementtype.method , elementtype.type}) @Retention (retentionpolicy.runtime) public @interface sxtmyannotation {String studentname () Default ""; int age () default 18;int ID () default-1; String[] Schools () default {"Tsinghua University", "Hubei College"};}


Package Com.lyy.test.annotion;import Java.lang.annotation.elementtype;import java.lang.annotation.Retention; Import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Target (Value={elementtype.method , elementtype.type}) @Retention (retentionpolicy.runtime) public @interface SxtAnnotation2 {String value ();}



The most common is @target and @retenion two meta-annotations







4. Small case

Use reflection to read the information of annotations and simulate the process of processing annotation information


<span style= "FONT-SIZE:14PX;" >package com.lyy.test.annotion;import java.lang.annotation.annotation;/** * Use reflection to read the information of annotations, simulate the process of processing annotation information * @author Lyy * */public class Demo3 {public static void main (string[] args) {try {class CLS = Class.forName ("Com.lyy.test.annotion.Studen T ");//gets all annotations of the class annotation[] annction =  cls.getannotations (); for (Annotation a:annction) {System.out.println (a);} Gets the annotations specified in the Class Table tab = (table) cls.getannotation (Table.class); System.out.println (Tab.value ());//Gets the annotation of the property of the class Java.lang.reflect.Field F = Cls.getdeclaredfield ("Studentname"); Field FX = f.getannotation (Field.class); System.out.println (Fx.columname () + "=====" +fx.type () + "=====" +fx.length ());//based on the table name obtained, the information of the field, the spelling of the DDL statement, and then, Execute this SQL using JDBC, generate the related table in the database} catch (Exception e) {e.printstacktrace ();}}} </span>


Package com.lyy.test.annotion: @Table ("Tb_student") public class Student {@Field (columname= "id", type= "int", length= ) private int id; @Field (columname= "sname", type= "varchar", length=100) private String studentname; @Field (columname= "Age", type= "int", length=3) private int age;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getstudentname () {return studentname;} public void Setstudentname (String studentname) {this.studentname = Studentname;} public int getage () {return age;} public void Setage (int.) {this.age = age;} <strong>}</strong>

Package Com.lyy.test.annotion;import Java.lang.annotation.elementtype;import java.lang.annotation.Retention; Import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.target;import javax.lang.model.element.Element; @Target (Value={elementtype.type}) @Retention (retentionpolicy.runtime) public @ Interface Table {String value ();}

Package Com.lyy.test.annotion;import Java.lang.annotation.elementtype;import java.lang.annotation.Retention; Import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Target (Value={elementtype.field} ) @Retention (retentionpolicy.runtime) public @interface Field {String columname (); String type (); int length ();}


Output Result:



Of course, the use of custom annotations is not possible, you will find that when we define these custom annotations, it seems that there is no effect, this is because the annotations do not take effect, we need to use reflection to parse the annotation into effect, this will be detailed in the next article!


With this in mind, you'll find that this is not like the hibernate principle, using annotations to identify, get table names, fields, and types using reflection, and then dynamically create SQL statement encapsulation, and finally to the programmer, if you do more, you can also make a simple Hibernate, learn these found themselves as if found a fun thing, learning, refueling!


Case Download: http://download.csdn.net/detail/qq_14996421/9539972


annotaion annotation Detailed case

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.