What is Annotation?
Annotation is translated into Chinese as annotation, which means to provide additional data information in addition to the logic of the program itself. Annotation has no direct impact on the annotated code. It cannot directly interact with the annotated code, but other components can use this information.
Annotation information can be compiled into a class file, or it can be retained in the Java virtual machine so that it can be obtained at runtime. Annotation can even be added to Annotation itself.
Those objects can be added with Annotation
Classes, methods, variables, parameters, and packages can be added Annotation.
Built-in Annotation
@Override OverloadingThe @Deprecated method or type annotated in the parent class is no longer recommended for use
@SuppressWarnings Prevent compile-time warning messages. It needs to receive an array of String as a parameter. The available parameters are:
unchecked
path
serial
finally
- ##fallthrough
@Retention
To determine thelifecycle of the Annotation being saved, you need to receive an Enum object RetentionPolicy as a parameter.
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME }
@Documented Documented
@Target
Indicates the range that the Annotation can modify, and receives an Enum object EnumType array as parameter.public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE }
@Inherited
This Annotation can affect subclasses of the annotated class. Customized AnnotationWe can customize Annotation after JSE5.0. Here is a simple example.@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodAnnotation { }The following Person object uses a custom MethodAnnotation.
public class Person { public void eat() { System.out.println("eating"); } @MethodAnnotation public void walk() { System.out.print("walking"); } }We can obtain Annotation information through reflection.
Class<Person> personClass = Person.class; Method[] methods = personClass.getMethods(); for(Method method : methods){ if (method.isAnnotationPresent(MethodAnnotation.class)){ method.invoke(personClass.newInstance()); } }Output:
walkingWe can also add methods to custom Annotation.
@Target(ElementType.TYPE) public @interface personAnnotation { int id() default 1; String name() default "bowen"; }The following is the use of personAnnotation.
@personAnnotation(id = 8, name = "john") public class Person { public void eat() { System.out.println("eating"); } @MethodAnnotation public void walk() { System.out.print("walking"); } }How Annotation is processedWhen the Java source code is compiled, a plug-in annotation processor of the compiler will process these annotations. The processor can generate report information or create additional Java source files or resources. If the annotation itself is added with the RententionPolicy runtime class, the Java compiler will store the metadata of the annotation in the class file. Then, the Java virtual machine or other programs can look up this metadata and process it accordingly. Of course, in addition to the annotation processor that can handle annotation, we can also use reflection to handle annotation ourselves. Java SE 5 has an
interface called AnnotatedElement. Java's reflective object classes Class, Constructor, Field, Method and Package all implement this interface. This interface is used to represent the annotated program elements currently running in the Java virtual machine. Through this interface, you can use reflection to read annotations. The AnnotatedElement interface can access annotations marked with RUNTIME. The corresponding methods are getAnnotation, getAnnotations, and isAnnotationPresent. Because Annotation types are compiled and stored in binaries just like classes, the Annotations returned by these methods can be queried just like Querynormal Java objects.
Wide use of AnnotationAnnotation is widely used in variousframeworks and libraries. Here are some typical applications.
JunitJunit is a very famousunit testing framework. When using Junit, you need to be exposed to a lot of annotations.
- @Runwith custom test class Runner
- @ContextConfiguration Set Spring’s ApplicationContext
- @DirtiesContext Reload the ApplicationContext before executing the next test.
- @Before Initialize before calling the test method
- @After Process after calling the test method
- @Test indicates that the method is a test method
- @Ignore can be added to the test class or test method to ignore the operation.
- @BeforeClass: Called before all test methods in the test class are executed, and only called once (the marked method must be
static)
@AfterClass: Called after all test methods in the test class have been executed and only executed once (the marked method must be static)
Spring
Spring is known as configuration hell, and there are many Annotations.
@Service Add annotations to the service class
@Repository Add annotations to the DAO class
@Component Add annotations to component classes
@Autowired Let Spring automatically assemble beans
@Transactional Configure things
@Scope Configure the object survival scope
@Controller Add annotations to the controller class
-
@RequestMapping url path mapping
@PathVariable Maps method parameters to paths
@RequestParam Binds request parameters to method variables
@ModelAttribute is bound to the model
@SessionAttributes is set to the session attribute
Hibernate
@Entity Modifies the entity bean
@Table Maps the entity class to the table in the database
@Column Mapping column
@Id mapping id
@GeneratedValue This field is self-increasing
@Version version control or concurrency Control
@OrderBy Sorting Rules
@Lob Large Object Annotation
Hibernate and a lot more The annotations about the union and the annotations of inheriting are not meaningful to list here.
JSR 303 – Bean Validation
JSR 303 – Bean Validation is a data validation specification, and its verification of Java beans is mainly implemented through Java annotation.
@NullThe element annotated by must be null
@NotNull annotated The element must not be null
@AssertTrueThe annotated element must be true@AssertFalseThe annotated element must be false@Min(value)The annotated element must be a number whose The value must be greater than or equal to the specified minimum value
@Max(value)The annotated element must be a number, and its value must be less than or equal to the specified maximum value
@DecimalMin(value)The annotated element must be a number, and its value must be greater than or equal to the specified minimum value
@DecimalMax(value)The annotated element must be Is a number whose value must be less than or equal to the specified maximum value
@Size(max, min)The size of the annotated element must be within the specified range
@Digits (integer, fraction) The annotated element must be a number, and its value must be within the acceptable range
@Past The annotated element must be Is a past date
@FutureThe annotated element must be a future date
@Pattern(value)The annotated element Must conform to the specified regular expression
In fact, there are many frameworks or libraries that use annotation, so I won’t list them one by one here. I hope everyone can draw inferences. Learn more about annotations in Java.
The above is the detailed content of Detailed explanation of Java Annotation features. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor