In Java, Annotation is introduced in Java 5 and is used to describe the meta information of Java code. Usually, annotations will not directly affect the execution of the code, although some annotations can be used to affect the execution of the code.
What can be done with annotations
Annotations in Java usually play the following roles
in
Annotation basics
A simple Java annotation is similar to @Entity. Where @ means telling the compiler that this is an annotation. Entity is the name of the annotation. Usually in a file, the writing method is as follows
public @interface Entity {
}
Annotation elements
Java annotations can use elements to set some values, and the elements in the annotations are similar to attributes or parameters. Sample code for defining annotation containing elements
public @interface Entity {
String tableName();
}
Sample code using annotation containing elements
@Entity(tableName = "vehicles")
The element name of the above annotation is tableName and the value set is vehicles. Annotations without elements do not require parentheses.
If the annotation contains multiple elements, the use method is as follows
@Entity(tableName = "vehicles", primaryKey = "id")
If the annotation has only one element, we usually write it like this
@InsertNew(value = "yes")
But in this case, if and only if the element name is value, we can also abbreviate it, that is, there is no need to fill in the element name value, the effect is as follows
@InsertNew("yes")
Annotation usage
Annotations can be used to modify these elements in the code
A complete example of usage is as follows
@Entitypublic 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 for the compiler. They are
@Deprecated
Can be used to mark classes, methods, and properties.
If the above three elements are no longer used, use the @Deprecated annotation. If the code uses the class, method or property of the @Deprecated annotation, the compiler will warn you.
@Deprecated is very simple to use, as follows: annotation of a deprecated class.
@Deprecatedpublic class MyComponent {}When we use the @Deprecated annotation, it is recommended to use the corresponding @deprecated JavaDoc symbol in conjunction with it and explain why this class, method or property is deprecated and what is the alternative.
@Deprecated/** @deprecated This class is full of bugs. Use MyNewComponent instead.*/public class MyComponent {}@Override
The @Override annotation is used to modify the method of rewriting the parent class. If a method that does not override the parent class uses this annotation, the compiler will prompt an error.
In fact, @Overide is not necessary to override the methods of the parent class or interface in a subclass. However, it is still recommended to use this annotation. In some cases, assuming that you modify the name of the parent class method, the subclass method that was rewritten before will no longer be rewrite. Without @Overide, you will not notice the method of this subclass. With this annotation modification, the compiler will prompt you with this information.
Examples of using Override annotation
public class MySuperClass { public void doTheThing() { System.out.println("Do the thing"); }}public class MySubClass extends MySuperClass{ @Override public void doTheThing() { System.out.println("Do it differently"); }}@SuppressWarnings
@SuppressWarnings is used to suppress the compiler from generating warning messages.
The elements that can be modified are classes, methods, method parameters, attributes, and local variables
Usage scenario: When a method calls a deprecated method or performs an unsafe type conversion, the compiler will generate a warning. We can add to this method
@SuppressWarnings annotation to suppress compiler generation warnings.
Note: Use @SuppressWarnings annotation and adopt the principle of proximity. For example, if a method has a warning, we try to use @SuppressWarnings to annotate this method, rather than annotating the class where the method is located. Although both can suppress the compiler from generating warnings, the smaller the scope, the better, because the scope is larger, which is not conducive to discovering warning information from other methods under this class.
Example of usage
@SuppressWarningspublic void methodWithWarning() {}Create your own annotations
In Java, we can create our own annotations, annotations and classes, and the interface files are defined in our own file. as follows
@interface MyAnnotation { String value(); String name(); int age(); String[] newNames();}The above code defines an annotation called MyAnnotation, which has 4 elements. Again, the keyword @interface is used to tell the java compiler that this is an annotation.
If you look closely, you will find that the definition of annotation elements is very similar to the interface method. These elements have types and names. These types can be
The following are the app custom annotations
@MyAnnotation( value="123", name="Jakob", age=37, newNames={"Jenkov", "Peterson"})public class MyClass {}Note that we need to set values for all annotation elements, and no one can be missing.
Annotation element default value
For elements in annotations, we can set default values for them, using the method
@interface MyAnnotation { String value() default ""; String name(); int age(); String[] newNames();}In the above code, we set the default value of the value element to an empty string. When we are using it, we can not set the value, that is, let the value use the default value of the empty string. Use sample code
@MyAnnotation( name="Jakob", age=37, newNames={"Jenkov", "Peterson"})public class MyClass {}@Retention
@Retention is an annotation used to modify annotation. Using this annotation, we can do it.
Control whether annotations are written to the class file to control whether annotations in the class file are visible at runtime
Control is simple, just use one of the following three strategies.
RetentionPolicy.SOURCE indicates that the annotation only exists in the source code, does not exist.class files, and cannot be visible during runtime. Common annotations are @Override, @SuppressWarnings.
RetentionPolicy.CLASS This is the default annotation retention policy. Under this strategy, annotations will exist with the .class file, but cannot be accessed at runtime. Usually this annotation strategy is used to operate at some bytecode level.
RetentionPolicy.RUNTIME can be accessed at runtime under this policy. Often, we do something in combination with reflection.
Example of use of @Retention
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)@interface MyAnnotation { String value() default "";}@Target
Using @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 shows that the MyAnnotation annotation can only modify the method.
@Target can select the parameter values as follows
@Inherited
If you want a class and its subclass to contain an annotation, you can use @Inherited to modify this annotation.
java.lang.annotation.Inherited@Inheritedpublic @interface MyAnnotation {}12@MyAnnotationpublic class MySuperClass { ... }1public class MySubClass extends MySuperClass { ... }The general meaning of the above code is
1. Use @Inherited to modify the annotation
2. Annotation of MySuperClass using MyAnnotation
3. Implement a class MySubclass inherits from MySuperClass
Through the above steps, MySubClass also has MyAnnotation annotation.
These are some basic concepts about the annotations in Java.
The above is the sorting of annotations in Java. We will continue to add relevant information in the future. Thank you for your support for this site!