I. About the notes
1.1 Introduction
Java Annotations are special syntactic structures that embed metadata in code. They do not directly affect the operation of the code, but can be used by tools and frameworks to provide additional information that can be processed at compile, deploy, or runtime.
Beginners can understand annotations in this way: Imagine that the code has a life, and annotations are labels that are attached to certain living individuals in the code. In simplified terms, an annotation is like atab (of a window) (computing)。
1.2 Development
The development of Java annotations can be traced back to the release of Java 5.0, which introduced annotations as a feature that provided developers with a new form of metadata, allowing type information to be added to code without changing the logic of the program. Here are some key milestones in the development of Java annotations:
-
Java 5.0 (2004) : Introduced the concept of annotations, including
@Override
,@Deprecated
,@SuppressWarnings
and other built-in annotations. -
Java 6.0 (2006) : Added meta-annotation support for annotations such as
@Retention
,@Target
,@Documented
, these meta annotations can be used to define metadata for other annotations. -
Java 7.0 (2011) : Introduced
@SafeVarargs
cap (a poem)@FunctionalInterface
annotation to provide compile-time checks on variable parameters and functional interfaces. -
Java 8.0 (2014) : Introduced
@Repeatable
annotations, allowing the same annotation type to be used multiple times on a single element. At the same time, Java 8 was also the period when the Spring Framework began to make extensive use of annotations, such as the@Autowired
,@RestController
etc. -
Java 11.0 (2018) : In this release, the Java module system (the Jigsaw project) was officially made part of Java, introducing the
@Module
,@Requires
,@Exports
and other module-related annotations. -
Evolution of the Spring Framework: from Spring's
@Transactional
cap (a poem)@ManagedResource
Starting , the Spring Framework gradually introduced more annotations to simplify configuration and improve development efficiency . By the time Spring , introduced the@Configuration
,@ComponentScan
,@EnableAutoConfiguration
and other annotations, further contributing to the popularity of annotated programming. -
Spring (2013) : Introduced
@Conditional
annotations, which allow the creation of beans based on conditions, are at the heart of autoconfiguration in Spring Boot. -
Spring (2017) : Introduced
@Indexed
annotations for improving annotation-driven component scanning performance.
The development of Java annotations not only improves code readability and maintainability, but also provides developers of frameworks and libraries with powerful tools that enable them to create more flexible and powerful APIs.As the Java language and related frameworks continue to advance, annotations will continue to play an important role in software development.
1.3 Characteristics
Java annotations are a powerful tool that makes the code more clear , modular , and can work closely with the compiler , development tools and run-time environment to improve development efficiency and code quality .
vantage
-
Enhanced code readability
- Annotations provide clear metadata, making code easier to understand, especially when using frameworks, and reducing dependence on XML configuration.
-
Reduce sample code
- Using annotations can reduce the amount of sample code and simplify configuration. For example, in the Spring Framework, annotations can be used to replace cumbersome XML configuration.
-
Compile-time checking
- With the annotation processor, you can check the use of annotations at compile time to help developers find problems early and improve code quality.
-
dexterity
- Annotations can be used in conjunction with a variety of programming paradigms, such as object-oriented programming, cutter-oriented programming, etc., providing developers with a flexible programming approach.
-
Support for metaprogramming
- Annotations, in combination with reflection mechanisms, can dynamically handle metadata at runtime and are suitable for the design of many frameworks and libraries, such as ORM and dependency injection.
-
Customization capabilities
- Developers can create custom annotations as needed to flexibly define metadata to meet specific needs.
drawbacks
-
performance overhead
- Reading annotations using the reflection mechanism may incur a performance overhead, especially in large-scale applications where frequent reflection calls can affect operational efficiency.
-
Difficulty in debugging
- The use of annotations can complicate the debugging process, especially if the effect of the annotation is not clearly identified in the error message, which can lead to confusion when tracing the problem.
-
learning curve
- For beginners, understanding annotations and their usage may require some learning costs, especially when annotations are used in combination with reflection.
-
overuse
- Overuse of annotations can lead to code that is difficult to maintain and understand, especially when multiple annotations are overlaid on the same element, which can complicate the logic.
-
Compiler Support
- Not all IDEs and tools fully support the writing and use of annotations, which may lead to some compatibility issues.
-
Not applicable to all scenarios
- In some simple scenarios, the use of annotations may seem overly complex, instead increasing the cost of development and maintenance.
1.4 Scenarios of use
Java annotations are used in many scenarios, for example:
-
Code Analysis Tools: For example, using
@Deprecated
Marking methods as obsolete helps developers identify risks and improve code. - Compile-time processing: For example, through custom annotations that generate helper code at compile time, such as the Lombok library.
- run-time processing: Through the reflection mechanism, annotation information can be obtained and processed at runtime to achieve dynamic behavior.
II. Basic grammar
The syntax of Java annotations includes defining annotations, using annotations, and meta-annotations. The following is an example and explanation of the syntax:
2.1 Defining Annotations
utilization@interface
The keyword defines an annotation. Elements (attributes) and default values can be defined.
public @interface MyAnnotation {
// Define an element of type String with a default value
String value() default "default value";
// Define an element of type integer with default value
int count() default 0; // Define an integer element with a default value.
}
2.2 Annotated Meta-Annotations
Meta annotations are annotations used to annotate other annotations.Java provides the following meta annotations:
- @Retention: Define the life cycle of the annotation.
- @Target: Defines which Java elements (classes, methods, fields, etc.) the annotation can be applied to.
- @Documented: Indicates that the annotation should be documented by the javadoc tool.
- @Inherited: Indicates that the annotation can be inherited by subclasses.
import ;
import ;
import ;
import ;
@Retention() // Annotations are available at runtime.
@Target() // Annotations can be used in methods.
public @interface MyMethodAnnotation {
String description(); }
}
2.3 Using annotations
When using custom annotations, just add the annotation directly to the desired element.
public class MyClass {
@MyMethodAnnotation(description = "This is a custom method annotation")
public void myAnnotatedMethod() {
// method implementation
}
}
2.4 Access Notes
Use the reflection mechanism to access annotation information at runtime.
import ;
public class AnnotationExample {
public static void main(String[] args) throws Exception {
Method method = ("myAnnotatedMethod");
if (()) {
MyMethodAnnotation annotation = ();
("Description: " + ());
}
}
}
2.5 Combination annotations
Multiple annotations can be used in combination.
@MyAnnotation
@AnotherAnnotation
public class AnotherClass {
// class implementation
}
Java preconfigured annotations
Java provides a number of predefined annotations that are very commonly used in Java development. The following are some of the major predefined annotations and their uses:
1. @Override
-
use: Used to indicate that a method overrides a method of a superclass.
-
typical example:
@Override public String toString() { return "This is my object"; }
2. @Deprecated
-
use: Marks an element (class, method, or field) as not recommended for use and may be removed in a future release.
-
typical example:
@Deprecated public void oldMethod() { // Not recommended }
3. @SuppressWarnings
-
use: Suppress specific warnings issued by the compiler. You can specify the type of warning, such as unused variables, unchecked conversions, etc.
-
typical example:
@SuppressWarnings("unchecked") public void myMethod() { List list = new ArrayList(); // Compiler may issue unchecked conversion warnings }
4. @FunctionalInterface
-
use: Used to indicate that an interface is functional, i.e., that the interface contains only one abstract method.
-
typical example:
@FunctionalInterface public interface MyFunctionalInterface { void execute(); }
5. @SafeVarargs
-
use: Used to indicate that variable-argument methods are type-safe for immutable generalizations.
-
typical example:
@SafeVarargs public static <T> void safeMethod(T... elements) { // process element }
6. @Native
-
use: Marks a field as a local constant, typically used to interact with C/C++ code.
-
typical example:
@Native public static final int NATIVE_CONSTANT = 100;
IV. Examples
Example 1 - Using annotations (marking obsolete methods)
In Java, using the@Deprecated
Annotations can mark a method or class as obsolete, encouraging developers to use the new implementation or method.
class DeprecatedExample {
@Deprecated
public void oldMethod() {
("This method is deprecated.");
}
public void newMethod() {
("This is the new method.");
}
public static void main(String[] args) {
DeprecatedExample obj = new DeprecatedExample();
// Calling obsolete methods
();
// Calling new methods
();
}
}
In this example, theoldMethod
is marked as obsolete, and when we call it we get a compiler warning to not continue using the method.
Example 2-Custom Annotations
1. Define annotations
// The meta annotation target, required for custom annotations, specifies the annotation's scope (here it is specified to work on classes and methods)
@Target({, })
// The meta annotation retention declares when the annotation will take effect (here it is at runtime).
@Retention()
public @interface MyAnnotation {
// Parameters need to be declared in the annotation, in the format: parameter type + parameter name();
String value() default "";
}
2. Use annotations
public class CustomAnnotation {
@MyAnnotation(value = "This is a test method")
public void test() {
("fulfillment test methodologies");
}
}
3. Getting and using annotation information
public class AnnotationDemo {
public static void main(String[] args) {
try {
// gain CustomAnnotation class Class boyfriend
Class<CustomAnnotation> clazz = ;
// gain test methodologies
Method method = ("test");
// 检查该methodologies是否有 MyAnnotation explanatory note
if (()) {
// gain MyAnnotation explanatory note
MyAnnotation annotation = ();
// 打印explanatory note的 value (be) worth
("explanatory note的(be) worth: " + ());
}
// call (programming) test methodologies
CustomAnnotation customAnnotation = new CustomAnnotation();
();
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}