Considerations raised by Java annotations

Source: Internet
Author: User

Since JDK5 began to add support for metadata (MetaData), which is annotation (Annotation), there are four basic annotations to JDK7, adding a new @safevarargs.


@Override annotation Callout A subclass overrides a method of the parent class, and if there is no such method in the parent class, the compiler will error.

@Deprecated Annotations Act on methods, classes, interfaces, table names this content has passed, is not recommended to use? But it is also available for labeling;

@SupressWarnings annotations are used to suppress compiler warnings, such as when using a collection, if you do not specify a generic type, there will be a warning message;

@SafeVarargs the note appears in JDK7, indicating "heap pollution" warning;

"Heap pollution" is to assign a non-generic variable to a variable with a generic type, which will cause the generic variable to be contaminated, and if you do not add the above annotations, the compiler will give hints to avoid runtime exceptions.


Let's say a simple example of how to customize annotations, before customizing annotations you need to know about meta annotations: annotate annotations.



Let's implement an example of a test class that specifies which methods can be tested in a class, and the mechanism that the method begins with test in JUnit can be tested by annotations.

design ideas;

1. Design Note class

2. Tool classes for parsing annotation classes

3. Classes that use annotations


Testannotation Annotation Class

ElementType, Retentionpolicy are enumerated classes, that is, if a member variable of a class is a few fixed values, you can use an enum//annotation to save to the runtime, you can read the annotation @retention by reflection ( Retentionpolicy.runtime)//can only be applied to the method above. @Target (elementtype.method) public @interface testannotation {String name () The default "Lilongsheng"; int age () default 25;}
in the above program, the attribute value of the annotation is stored in the enumeration class, which we can think of, we define the annotation when the property is also saved early enumeration inside, if this design can let a method to implement many functions, such as adding and removing changes only need to be more enumerated worthy type 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 ();// Traverse all the methods inside the Clazz corresponding class for (method M:class.forname (Clazz). GetMethods ()) {//If the method uses @testannotation-Modified if ( M.isannotationpresent (Testannotation.class)) {try {//Execute annotated method M.invoke (o);} catch (Exception e) {e.printstacktrace () ; System.out.println ("Method" +m+ "Run 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 of commenting is executed, which is the definition of the annotation to control which methods can be tested, which ones are not tested, the obvious benefit of annotations is decoupling, annotations are given to program-specific functions, such as generating XML files in Hibernate, transaction control, etc. are implemented by annotations.


However, the XML file generation annotations in Hibernate are not generated by reflection, but are implemented using the APT tool class, which requires the retentionploliy of annotations to be set to source.

Note blocks have been introduced in the familiar framework of spring, struts, Hibernate, SPRINGMVC, EJB, and so on, and more and more frameworks have introduced annotations, which are a lot more than a bunch of configuration files, spring AOP, The IOC and other mechanisms deserve our deep research.


these days take a closer look at the JDK package inside the class, it is a lot of things worthy of our serious study, look at the time you will feel the more things inside, the above using the method class, class, these two classes are often used to also very useful, class forname (), Newinstance () Two methods are often used, the method class can obtain all the methods in a class, including the method that it inherits from the object root class, such as GetClass, Hascode (), etc. By looking at the object class Discovery GetClass () method with the final decorated table name this method can not be overridden by the quilt class, this method may be a number of objects of the class, and then get the class load class, classpath can be obtained in this way.

By the way also look at the generics in JDK7, there are some differences between the generic syntax and the JDK6 in JDK7, which are more concise, for example, in JDK6 vs. JDK7

Jdk6.0list<string> list=new arraylist<string> ();//jdk7.0list<string> list=new ArrayList< > ();
The syntax of JDK7 is concise, it is not necessary to specify the type in the constructor, there are many generics to improve the use of Java performance, but also look at the low-efficiency platform of the underlying generics, methods, interface encapsulation.

Considerations raised by Java annotations

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.