Author's Message
Hello, everyone, this is my first article. I hope to summarize the knowledge I have learned and share it with you. I will share it with you in the next period of time. Publish a series of Java, Python and other entry-level related articles, and share them systematically so that you can go further by laying a solid foundation. I hope you all will give me some advice! Without further ado, let’s get down to the practical stuff! (If there is any infringement involved, please contact me through this platform to delete)
Preface
XML as a configuration file is popular among most programmers However, some people prefer to use annotations. In fact, I personally feel that the choice is not the point. The point is to understand the essence of the birth of each technology; XML as a configuration file and code is a "loosely coupled" code description, but when XML configuration When there are too many files, it is difficult to manage. At the same time, the IDE cannot verify the correctness of the XML configuration file, which increases the difficulty of testing. Annotations are "tightly coupled" code descriptions. Its purpose is to make the application easier to expand while also "Zero" configuration.
1. What is annotation
Annotation is annotation, which is the metadata in the code (metadata: data describing the data). By using annotation, Program developers can embed some supplementary information in the source files without changing the original logic. Please take a look at the following code snippet:
For beginners, in fact, they often see similar code and wonder what the hell is @Override? In fact, it is an annotation. Adding @Override to the toString() method means that the toString() method under the annotation must reconstruct the parent class method.
After seeing this, I think some people will think that I will introduce various annotations to you next? ! I don't!
2. Grammar standards of annotation types
Annotations are a special type in Java. Next, let’s take a look at how to design an annotation type.
1. Grammar standard:
public @interface 注解類型名稱 { [ 數(shù)據(jù)類型 變量名 () [ default 初始值 ]; ] }
Note:
1) The content in "[ ]" is optional. If the annotation is empty inside, it means the current annotation Annotate the logo.
2) Annotations should intelligently include variables and cannot include methods.
3) Annotations are special marks in the code and cannot be used alone. They need to be used together with classes or interfaces.
4) Annotation types can be used to set metadata for program elements (program elements: classes, methods, member variables, etc.).
2. Case: Design the annotation type Testable, and the method identified by this annotation is a testable method. The annotation is empty internally, indicating that the annotation is an identification annotation.
public @interface Testable { }
public class Test { @Testable public void info() { System.out.println(“我是info方法”); } public void info1() { System.out.println(“我是info1方法”); } }
The @Testable annotation is added to this class to indicate that the info method is an executable method. It only describes that the method is an executable method and does not have any dynamic interaction capabilities. If you want To achieve the function of this annotation, a supporting Java application must be written. For specific code, please refer to the following code.
You can think about it, if we want to parse the internal structure of a class, what technology can we use to achieve it?
The answer is: reflection mechanism (for friends who are unclear about the reflection mechanism in the following paragraph, please follow the code below to debug. The specific knowledge about the reflection mechanism will be released later).
Common tool classes with reflection function in the java.lang.reflect package: Method (method class), Field (field class), Constructor (constructor method class), etc.
The above tool classes expand the ability to read runtime annotations, that is, implement the java.lang.annotation.AnnotatedElement interface; this interface is the parent interface of all program elements, and this interface provides functions for obtaining annotations information related methods.
getAnnotation(Class
annotationClass): Returns the annotation of the specified type on the program element. If the annotation of this type does not exist, returns null Annotation [] getAnnotations(): Returns all annotations that exist on the program element.
Annotation is the parent interface of all annotations. By default, any interface type implements this interface.
boolean isAnnotationPresent(Class Extends Annotation> annotationClass): Determines whether the program element contains annotations of the specified type. If it exists, it returns true, otherwise it returns false.
Code reference:
Parse the Test class and execute the method marked with @Testable.
import java.lang.reflect.Method; public class UseTest { public static void main(String[] args)throws Exception { Class c=Class.forName(“Test”); Object o=c.newInstance(); Method[] me=c.getDeclaredMethods(); for(Method temp:me) { if(temp.isAnnotationPresent(Testable.class)) temp.invoke(o,new Object[0]); } } }
Okay, now you can run the program to see the effect!
. . . . . . .
Isn’t it particularly speechless (ˉ▽ˉ;)..., by executing the code, you will find that the program has no results, which is different from what we thought? !
If you want to know what happened next time, please read the breakdown next time!
3. Summary:
Next, let us summarize the knowledge points that friends need to master.
1. The difference between XML and annotations
2. What are annotations
3. Grammar standards for annotation design
4. Reflection mechanism
5. Methods and functions of java.lang.annotation.AnnotationElement
4. Conclusion
Let me tell you the reason why I ended in a hurry. This is the first time When I write an article, I don’t know what the content format will be like. Please read the next article for the remaining relevant knowledge. Thank you for your support.
The above is the detailed content of Java annotations - Java's own configuration files. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.
