Thinking Caused by JAVA annotations and Thinking Caused by JAVA annotations

Source: Internet
Author: User

Thinking Caused by JAVA annotations and Thinking Caused by JAVA annotations

Java has added support for MetaData (MetaData) Since JDK5, that is, Annotation. By JDK7, there have been four basic annotations and a new @ SafeVarargs is added.


@ Override annotation indicates that a subclass overrides a method of the parent class. If the parent class does not have this method, the compiler reports an error;

@ Deprecated the annotation acts on methods, classes, and interfaces. The table name has passed and is not recommended? However, tags can also be used;

@ SupressWarnings annotation is used to suppress the warning information of the compiler. For example, if you do not specify a wildcard when using a set, there will be warning information;

@ SafeVarargs This annotation appears in JDK 7, indicating a "heap pollution" Warning;

"Heap pollution" means assigning a variable without generics to a variable with generics, which will lead to the contamination of generics. Without the surface annotation, the compiler will give a prompt, avoid running exceptions.


Let's use a simple example to describe how to customize annotations. Before using a custom annotation, we need to understand the Metadata Annotation: Add annotation to the annotation.



Let's implement an example of a test class, specifying which methods can be tested in a class, in JUNIT, the method that starts with "test" can be tested. This mechanism is also implemented through annotations.

Design ideas;

1. Design annotation class

2. Tool class for parsing annotation classes

3. Use annotation classes


TestAnnotation annotation class

// ElementType and RetentionPolicy are enumeration classes. If a member variable of a certain type has several fixed values, you can use the enumeration // annotation to save it to the runtime, the annotation @ Retention (RetentionPolicy. RUNTIME) // it can only be applied to the method. @ Target (ElementType. METHOD) public @ interface TestAnnotation {String name () default "lilongsheng"; int age () default 25 ;}
In the above program, the property value of the annotation is saved in the enumeration class, which we can think of, when we define the annotation, we also save the attribute in the early enumeration, if this design is used, a method can implement many functions. For example, adding, deleting, modifying, and querying only requires more enumeration worthy types to judge.

/*** @ Description process the annotation * @ param clazz * @ throws ClassNotFoundException * @ throws InstantiationException * @ throws IllegalAccessException */public static void process (String clazz) throws ClassNotFoundException, InstantiationException, illegalAccessException {Object o = Class. forName (clazz ). newInstance (); // traverses all methods in the corresponding clazz Class for (Method m: Class. forName (clazz ). getMethods () {// if this method uses @ TestAnnotation to modify if (m. isAnnotationPresent (TestAnnotation. class) {try {// execute the method m marked with an annotation. invoke (o);} catch (Exception e) {e. printStackTrace (); System. out. println ("method" + m + "failed" + e. getCause ());}}}}

Test class

Public class MyClass {@ TestAnnotationpublic void method1 () {System. out. println ("test method 1") ;}@ TestAnnotationpublic void method2 () {System. out. println ("test method 2");} public void method3 () {System. out. println ("test method 3");} public void method4 () {System. out. println ("Test Method 4 ");}}

Execution result:


Only the method for adding comments is executed. This is to define comments to control which methods can be tested and which are not tested. One obvious benefit of annotation is decoupling, annotations give specific functions to the program. For example, xml files generated in Hibernate and transaction control are implemented through annotations.


However, annotations generated by xml files in Hibernate are not generated by reflection, but by using the APT tool class. You need to set the RetentionPloliy of the annotation to Source.

Annotation blocks are introduced in the frameworks we are familiar with, such as spring, struts, Hibernate, springmvc, and ejb. More and more frameworks have introduced annotations, compared with a large number of configuration files, we have introduced a lot of such mechanisms as aop and ioc in spring, which deserves further research.


Take a closer look at the classes in the JDK package over the past few days. There are many things worth learning. The more you read, the more you will feel, the Method Class and class Class are used frequently. The forName () and newInstance () methods in the class are often used, the Method class can obtain all the methods in a class, including the methods inherited from the Object root class, such as getClass and hascode (). getClass () can be found through the Object class () the method uses final to modify the table name. This method cannot be used to override the quilt class. This method can obtain the number of classes of an object and obtain the class loading Class and Class path.

After each Class is instantiated, a Class object will be generated. The getClass method is the method for getting this Class object, and there is a simpler direct (object. class), but if we only know one string, such as "person", we need to use the forName () reflection method to obtain it.

After obtaining the Class Object of the object, you can obtain all the information of the class, such as whether it is an interface, Class, annotation, method, and so on, and obtain all fields, methods, and annotations, you can also dynamically execute methods.

By the way, I also looked at the generics in JDK 7. in JDK 7, the generic syntax is different from that in JDK 6, which is more concise. For example, in comparison between JDK 6 and JDK 7

//JDK6.0List<String> list=new ArrayList<String>();//JDK7.0List<String> list=new ArrayList<>();
The syntax of JDK 7 is simplified. You do not need to specify the type in the constructor. In addition, many generics can be used to improve java performance, at the same time, we are also looking at the underlying generics, methods, and interface encapsulation in the efficient platform.


Important java annotations

The purpose of annotation is to describe the functions of a method, which is particularly important for large-scale projects. Because sometimes, not a person is writing this project. How do people understand this without annotations?

What are the differences between annotations and annotations in java?

First, there are three kinds of Annotations: // **/The first two compilers skipped directly and never read them. The third compiler is understandable, it is used when you use commands such as javadoc to generate APIs.

Note: This is all for the compiler. For example, @ Ovrride indicates that this method overwrites the methods in the parent class, rather than the custom ones. Therefore, the compiler will check whether your method name is the same as the parent class and whether it is wrong.

At first, annotations are relatively simple. Later, variables and parameters can be added to annotations to save code (these codes are accepted by everyone and replaced by a formula)

Annotation is a description of the computer, or you can write your own code to tell the computer compiler. Annotation is actually code, but it seems a little different from what we write. It is also part of the code. When learning Hibernate and Spring, it will use a lot of annotations to save a lot of code.

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.