Customize annotations in Java

Source: Internet
Author: User
Tags deprecated java se
Objective

With the popularity of Springboot, the previous XML-based spring configuration was used less and more, with more and more javaconfig forms, similar to the following:

@Configuration  Public class AppConfig {@Bean (name= "Hellobean")   public HelloWorld HelloWorld () {    ret  Urnnew  Helloworldimpl (); }}

It can be seen that more is implemented based on annotations (Annotation), including Springboot's entry class **application.

@Configuration @componentscan ("Com.alibaba.trade") @EnableAutoConfiguration//(exclude = {Pagehelperautoconfiguration.class})@ServletComponentScan @enabletransactionmanagement@enablediscoveryclient@enablewebmvc@mapperscan ("Com.alibaba.trade.shared.mapper") Public classTradeapplicationextendsSpringbootservletinitializer { Public Static voidMain (string[] args) {Springapplication.run (tradeapplication.class, args); }}

Java annotations not only allow us to reduce the XML files in our project, but also make our code more concise and easy to maintain. So how do we read the annotations and create our own annotations in the project?

Annotation description

Java annotations, also known as Java Annotations, are special syntax metadata that supports the addition of source code in the Java language version 5.0. Provides a formalized way for us to add information to our code so that we can use it very conveniently at a later point in time.
Classes, methods, variables, parameters, and packages in the Java language can be labeled. Unlike Javadoc, Java annotations can get annotations by reflection. Annotations can be embedded in bytecode when the compiler generates the class file. The Java Virtual machine preserves the annotation content and can get the annotation content at run time.

The annotation itself does not have a specific function, it is equivalent to a callout, and this callout specific role and meaning needs to be implemented by ourselves. It is generally first to determine whether a class or attribute is modified by the annotation and then by reflection to obtain the annotation properties and then realize the specific business functions.

Built-in annotations

Java defines a set of annotations, a total of 7, 3 in Java.lang, and 4 in Java.lang.annotation.
1, the function in the code annotation is

    • @Override-Check if the method is an overloaded method. If a parent class is found, or if the method is not in the referenced interface, a compilation error is reported.
    • @Deprecated-Mark obsolete methods. If you use this method, a compile warning is reported.
    • @SuppressWarnings-instructs the compiler to ignore the warnings declared in the annotations.

2. The annotations (or meta-annotations ) that function in other annotations are:

    • @Retention-Identifies how this annotation is saved, whether it is in code only, in class files, or at run time through reflection.
    • @Documented-Mark whether these annotations are included in the user's document.
    • @Target-Mark what kind of Java member this annotation should be.
    • @Inherited-Tag this annotation is inherited from which annotation class (the default annotation does not inherit from any subclasses)

3. Starting with Java 7, add 3 additional annotations:

    • @SafeVarargs-Java 7 starts with support, ignoring any warnings that result from a method or constructor call that uses a parameter as a generic variable.
    • @FunctionalInterface-Java 8 starts with support for identifying an anonymous function or a functional interface.
    • @Repeatable-Java 8 starts with support, identifying that an annotation can be used more than once on the same declaration.
Meta annotations

1.@Retention

@Retention Annotation Specify how tag annotations are stored:

    • Retentionpolicy.source-the annotations of the tag remain only at the source level and are ignored by the compiler.
    • Retentionpolicy.class-markup annotations are persisted by the compiler at compile time, but the Java Virtual Machine (JVM) is ignored.
    • Retentionpolicy.runtime-the comment of the token is reserved by the JVM, so it can be used by the runtime environment.

2.@Documented
@Documented Note that the Javadoc tool should be used to record these elements whenever the specified annotation is used (by default, comments are not included in Javadoc). For more information, see the Javadoc tools page.

3.@Target

@Target Comment marks another comment to limit the types of Java elements that can apply annotations. The destination comment Specifies one of the following element types as its value.

    • Elementtype.type can be applied to any element of the class.
    • Elementtype.field can be applied to fields or properties.
    • Elementtype.method can be applied to method-level annotations.
    • Elementtype.parameter can be applied to the parameters of the method.
    • Elementtype.constructor can be applied to constructors.
    • Elementtype.local_variable can be applied to local variables.
    • Elementtype.annotation_type can be applied to annotation types.
    • Elementtype.package can be applied to package declarations.
    • Elementtype.type_parameter
    • Elementtype.type_use

4.@Inherited
@Inherited Comment indicates that the annotation type can inherit from the superclass. When the user queries the comment type and the class does not have this type of comment, the class's superclass is queried to get the comment type (not by default). This comment applies only to class declarations.

5.@Repeatable
Repeatable introduced in Java SE 8, @Repeatable annotations indicate that annotations to tags can be applied more than once to the same declaration or type use (that is, they can be reused on the same class, method, property, and so on).

Custom annotations

In Java, custom annotations are similar to creating an interface, and custom annotations are formatted with @interface as flags.

@Documented @retention (retentionpolicy.runtime) @Target ({elementtype.type})  public @Interface  SPI {     /**    * Default extension name    * * default "";}      

We know that there is a annotation interface in the Java.lang.annotation package, which is the public interface for all annotation type extensions. Can we implement the custom annotations directly by implementing the interface?

Importpublicclassimplements  Annotation {     @Override      Public extends Annotation> Annotationtype () {    returnnull;    }}

Found that there is only one Annotationtype method in the annotation interface, and through annotation source comments we can find that the answer is not.

Translation is: Annotaion is inherited by all annotation types, but note that manually extending an interface that inherits this interface does not define the annotation type. Also note that this interface itself does not define the annotation type.

Usage Scenarios

Custom annotations Use a lot of scenes, we are building wheels to write the framework of the process is often used to, for example, I recently encountered a business scenario: like some editing business information interface, product requirements after the compilation of new and old value of information comparison, comparison of business functions, we realize the way is to get the front end filled form form (new value) and the DTO (old value) that is queried in the database gets the same attribute field name through reflection technology, and then compares the property value to get the new old value. We also know the field names in the dto of the field after we get the value, but how do I return the Chinese name of the new old value field to the front end? For example:

 Public class stedent {     private  String name;      Private int Age ;      Private String sex;      // Omit Setter,getter}

The result of our comparison is name: "Xiaoming", "daming", Age:24, 26. But we can't just return name and age to the front end, the format they need is: Name: "Xiaoming", "Daming", Ages: 26. At this point, you can consider customizing an annotation @FieldName ,

@Deprecated @documented@retention (retentionpolicy.runtime) @Target (Elementtype.field)  public @Interface  FieldName {    default "";}

Then add the note above the attribute field

 Public class Student {     = "name")    private  String name;      = "Age")    privateint ages ;      = "Gender")    private  String sex;      // Omit Setter,getter}

You can then get the name of the field by reflection.

//if the Oldfield property value is not the same as the content of the Newfield property valueif(!IsEmpty (NewValue)) {Map<string, object> map =NewHashmap<>(); String NewFieldName=Newfield.getname (); if(Newfield.isannotationpresent (Apimodelproperty.class) {apimodelproperty Apimodelpropertyanno= Newfield.getannotation (Apimodelproperty.class); NewFieldName=Apimodelpropertyanno.value (); Else if(Newfield.isannotationpresent (FieldName.class) {FieldName Fieldnameanno= Newfield.getannotation (FieldName.class); NewFieldName=Fieldnameanno.name ();        } map.put (Field_name, NewFieldName);        Map.put (Old_value, OldValue);        Map.put (New_value, newvalue); List.add (map);}

Related Article

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.