Annotations in Java and sample code _java

Source: Internet
Author: User
Tags deprecated reflection

In Java, annotations (Annotation) Introduce meta information that begins with Java5 to describe Java code, which typically does not directly affect the execution of code, although some annotations can be used to influence code execution.

What can annotations do

Annotations in Java typically play the following roles

    1. Compiler directives
    2. Build-time Directives
    3. Run-time Directives

which

    1. There are three compiler directives built into Java, which will be highlighted later in this article
    2. Java annotations can be applied at build time, when you build your project. The construction process includes generating source code, compiling source code, generating XML file, packaging the source code and file to jar package. Software builds are usually done automatically using tools such as Apache Ant and maven. These build tools scan Java code according to specific annotations, and then generate source code or files based on these annotations.
    3. Typically, annotations do not appear in the compiled code, but they are also possible if you want to appear. Java supports run-time annotations, which we can access with Java reflection, and the purpose of run-time annotations is usually to provide instructions to programs and Third-party APIs.

Annotation Basics

A simple Java annotation resembles the @entity. Where @ means to tell the compiler that this is an annotation. And entity is the name of the annotation. Usually in the document, the following is written

Public @interface Entity {
}

annotation element

Java annotations can use elements to set values that are similar to attributes or parameters in the annotation. Define the annotation sample code that contains the element

Public @interface Entity {
String TableName ();
}

Using the annotation sample code that contains the element

@Entity (tablename = "vehicles")

The element name for the above annotation is tablename and the value set is vehicles. Annotations that do not have elements need not use parentheses.

If the annotation contains more than one element, use the following method

@Entity (tablename = "vehicles", PrimaryKey = "id")

If the annotation has only one element, usually we are writing this way

@InsertNew (value = "yes")

But in this case, if and only if the element name is value, we can also abbreviate that there is no need to fill in the element name value, the effect is as follows

@InsertNew ("yes")

Annotations Use

Annotations can be used to modify these elements in the code

    1. Class
    2. Interface
    3. Method
    4. Method parameters
    5. Property
    6. Local variables

A full use example is shown below

@Entity public
class Vehicle {

  @Persistent
  protected String vehiclename = null;


  @Getter public
  String Getvehiclename () {return
    this.vehiclename;
  }

  public void Setvehiclename (@Optional vehiclename) {
    this.vehiclename = vehiclename;
  }

  Public list addvehiclenametolist (list names) {

    @Optional
    list localnames = names;

    if (localnames = = null) {
      localnames = new ArrayList ();
    }
    Localnames.add (Getvehiclename ());

    Return Localnames
  }

}

Built in Java annotations

There are three built-in annotations in Java that are used to provide instructions to the compiler. They are

    1. @Deprecated
    2. @Override
    3. @SuppressWarnings

@Deprecated

Can be used to mark classes, methods, properties.
If the above three elements are no longer in use, use the @deprecated annotation
If the code uses the class, method, or property of the @deprecated annotation, the compiler warns.

@Deprecated is simple to use, as follows is a deprecated class for annotations.

@Deprecated public
class MyComponent {

}


When we use the @deprecated annotation, we recommend that you use the corresponding @deprecated Javadoc notation and explain why this class, method, or property is deprecated and what the alternative scenario is.

@Deprecated
/**
 @deprecated This class are full bugs. Use Mynewcomponent instead.
*/Public
class MyComponent {

}

@Override

@Override annotations are used to decorate methods that override the parent class. If a method that is not overriding the parent class uses this annotation, the compiler prompts for an error.

In fact, the method of overriding a parent class or interface in a subclass @Overide is not necessary. However, it is recommended that you use this annotation, and in some cases, if you modify the name of the method of the parent class, the previously overridden subclass method will no longer be an override, and if there is no @overide, you will not perceive the method of the subclass. With this annotation modifier, the compiler will prompt you with this information.

Examples of using override annotations

public class Mysuperclass {public

  void dothething () {
    System.out.println (' Do the Thing ');
  }


The public class MySubClass extends mysuperclass{@Override the public
  void dothething () {
    System.out.println ( "Do it differently");
  }


@SuppressWarnings

@SuppressWarnings used to suppress the compiler from generating warning messages.

The elements that can be decorated are classes, methods, method parameters, attributes, local variables

Usage scenario: The compiler generates a warning when one of our methods invokes a deprecated method or makes an unsafe type conversion. We can add to this method

@SuppressWarnings annotations to suppress compiler generation warnings.

Note: Using the @suppresswarnings annotation, using the proximity principle, such as a method warning, we try to use the @suppresswarnings annotation method rather than the class where the annotation method resides. Although both can suppress compiler generation warnings, the smaller the scope the better, because the scope is large, which is not conducive to the discovery of other methods under the class warning message.

Using the sample

@SuppressWarnings public
void Methodwithwarning () {

}

To create your own annotations

In Java, we can create our own annotations, annotations and classes, and interface files as defined within our own files. As follows

@interface myannotation {
  String  value ();
  String  name ();
  int age   ();
  String[] Newnames ();
}

The code above defines an annotation called myannotation, which has 4 elements. Again, @interface this keyword is used to tell the Java compiler that this is an annotation.

With a closer look, you will find that the definition of the annotation element is very similar to the method of the interface. These elements have a type and a name. These types can be

    1. Raw data type
    2. String
    3. Class
    4. Annotation
    5. Enumeration
    6. One-dimensional arrays

The following are the annotations for applying custom

@MyAnnotation (
  value= "123",
  name= "Jakob",
  age=37, newnames={
  "Jenkov", "Peterson"}
)
public class MyClass {


}

Note that we need to set values for all the annotation elements, one for all.

Callout element Default value

For the elements in the annotation, we can set a default value for it, using the method

@interface myannotation {
  String  value () default "";
  String  name ();
  int age   ();
  String[] Newnames ();
}

For the above code, we set the default value of the value element to be an empty string. When we are in use, we can not set the value of values, that is, let value use the null string default value. Using the sample code

@MyAnnotation (
  name= "Jakob",
  age=37,
  newnames={"Jenkov", "Peterson"}
) public
class MyClass {

}

@Retention

@Retention is used to modify annotations, using this annotation, we can do

Controls whether annotations are written to a class file
Control whether the annotations in the class file are visible at run time

Control is simple, using one of the following three strategies.

Retentionpolicy.source indicates that the annotation exists only in the source code, does not exist. class files, and is not visible when run. The common annotation is @override, @SuppressWarnings.
Retentionpolicy.class This is the default annotation retention policy. Under this strategy, annotations will exist with the. class file, but they cannot be accessed by the runtime. This annotation policy is usually used to operate at some bytecode level.
Retentionpolicy.runtime This policy can be accessed at run time. Usually, we do something with reflection.

Examples of @Retention usage

Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;

@Retention (retentionpolicy.runtime)
@interface myannotation {
  String  value () default "";
}

@Target

Using the @target annotation, we can set which Java elements can be modified by custom annotations. Simple example

Import Java.lang.annotation.ElementType;
Import Java.lang.annotation.Target;

@Target ({Elementtype.method}) public
@interface myannotation {
  String  value ();
}

The above code demonstrates that myannotation annotations can only modify methods.

The parameter values that @Target can select are as follows

    1. Elementtype.annotation_type (Note: cosmetic annotations)
    2. Elementtype.constructor
    3. Elementtype.field
    4. Elementtype.local_variable
    5. Elementtype.method
    6. Elementtype.package
    7. Elementtype.parameter
    8. Elementtype.type (Note: Any type, that is, the type above can be decorated)

@Inherited

If you want a class and its subclasses to contain an annotation, you can use @inherited to modify the annotation.

java.lang.annotation.Inherited

@Inherited Public
@interface myannotation {

}
1
2
@ Myannotation public
class Mysuperclass {...}
1 public
class MySubClass extends Mysuperclass {...}

The general meaning of the above code is

1. Use @inherited to modify annotations Myannotation
2. Use myannotation annotation Mysuperclass
3. Implement a class mysubclass inherit from Mysuperclass

Through the steps above, MySubClass also has a myannotation annotation.

Some basic concepts about annotations in Java are these.

The above is on the Java annotation Data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.