Java Basics---annotations (Annotation)

Source: Internet
Author: User

First, the concept

Annontation is a new feature that Java5 started to introduce. Chinese names are generally called annotations. It provides a secure, comment-like mechanism for associating any information or metadata (metadata) with program elements (classes, methods, member variables, and so on). More generally it means adding a more intuitive and straightforward description of the elements of the program (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.

The Java.lang.annotation.Annotation interface is an interface that all annotation must implement.

System built-in annotation

@ Override

Java.lang.Override is a The marker annotation type, which is used as the 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 will alert you with a compilation error.

classperson{ PublicString GetInfo () {//Get information        return"This is a person class. " ; }};classStudentextendsperson{//inherit this class@Override PublicString GetInfo () {//Overwrite Method        return"This is a student class. " ; }}; Public classoverrideannotationdemo{ Public Static voidMain (String args[]) {person per=NewStudent ();    System.out.println (Per.getinfo ()); //Output Information    }};

Use @override annotations to ensure proper execution of programs

@Deprecated

deprecated is also a marker 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.

@Deprecated            //  declaration does not recommend the use of the action class  demo{    public  String GetInfo () {        return ' This is a person class. " ;    }};  Public class deprecatedannotationdemo02{    publicstaticvoid  Main (String Args[]) {        new  Demo ();        System.out.println (D.getinfo ());}    ;

@SuppressWarnings

This note can tell the Java compiler to turn off warnings for classes, methods, and member variables. Sometimes there are some warnings to compile, some hidden bugs for these warnings, some unavoidable, and some warning messages that you don't want to see can be masked by this annotation.

suppresswarning is not a marker 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.

@DeprecatedclassDemo<t>{    PrivateT var;  PublicT GetVar () {return  This. var; }     Public voidSetVar (T var) { This. var =var; }}; Public classsuppresswarningsannotationdemo03{@SuppressWarnings (value={"Unchecked", "deprecation"})     Public Static voidMain (String args[]) {Demo d=NewDemo (); D.setvar ("My My Yes") ; System.out.println ("Content:" +D.getvar ()); }};

Reflection and Annontation

If you want a annotation to work, you have to have a reflection mechanism

Examples such as the following

 Package org.lxh.demo16.reflectannotation;  Public class simplebeanone{    @SuppressWarnings ("Unchecked")     @Deprecated    @Override      public String toString () {        return "Hello oumyye!!!"  ;    }};

At the same time set three annotation, then note that only deprecated annotation definition range is the runtime range, so at this time through reflection can only get one.

Importjava.lang.annotation.Annotation;ImportJava.lang.reflect.Method; Public classreflectdemo01{ Public Static voidMain (String args[])throwsexception{//all exceptions ThrownClass <?> C =NULL ; C= Class.forName ("Org.lxh.demo16.reflectannotation.SimpleBeanOne") ; Method ToM= C.getmethod ("toString");//Find the ToString () methodAnnotation an[] = tom.getannotations ();//get all the annotation         for(Annotation A:an) {//using the foreach outputSystem.out.println (a); }    }};

At this point, a annotation has been made.

Java Basics---annotations (Annotation)

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.