current position:Home>Basic use of annotations in java development

Basic use of annotations in java development

2022-01-27 02:09:03 KarenChia

annotation

  • also called Java mark ,JDK5.0 An annotation mechanism introduced .
  • A form of metadata , Provide data about the program but not the program itself .
  • Annotations have no direct impact on the operation of the code they annotate .

Custom annotation

newly build Class When you file , choice Annotation:
 Insert picture description here
Definition grammar , Use @interface modification :

public @interface MyAnnotation {
    
    // TODO: 12/16/21 do something
    
}

stay Java In language , All annotations are implemented Annotation Interface :

/* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */

package java.lang.annotation;

/** * The common interface extended by all annotation types. Note that an * interface that manually extends this one does <i>not</i> define * an annotation type. Also note that this interface does not itself * define an annotation type. * * More information about annotation types can be found in section 9.6 of * <cite>The Java&trade; Language Specification</cite>. * * The {@link java.lang.reflect.AnnotatedElement} interface discusses * compatibility concerns when evolving an annotation type from being * non-repeatable to being repeatable. * * @author Josh Bloch * @since 1.5 */
public interface Annotation {
    
    /** * Returns true if the specified object represents an annotation * that is logically equivalent to this one. In other words, * returns true if the specified object is an instance of the same * annotation type as this instance, all of whose members are equal * to the corresponding member of this annotation, as defined below: * <ul> * <li>Two corresponding primitive typed members whose values are * <tt>x</tt> and <tt>y</tt> are considered equal if <tt>x == y</tt>, * unless their type is <tt>float</tt> or <tt>double</tt>. * * <li>Two corresponding <tt>float</tt> members whose values * are <tt>x</tt> and <tt>y</tt> are considered equal if * <tt>Float.valueOf(x).equals(Float.valueOf(y))</tt>. * (Unlike the <tt>==</tt> operator, NaN is considered equal * to itself, and <tt>0.0f</tt> unequal to <tt>-0.0f</tt>.) * * <li>Two corresponding <tt>double</tt> members whose values * are <tt>x</tt> and <tt>y</tt> are considered equal if * <tt>Double.valueOf(x).equals(Double.valueOf(y))</tt>. * (Unlike the <tt>==</tt> operator, NaN is considered equal * to itself, and <tt>0.0</tt> unequal to <tt>-0.0</tt>.) * * <li>Two corresponding <tt>String</tt>, <tt>Class</tt>, enum, or * annotation typed members whose values are <tt>x</tt> and <tt>y</tt> * are considered equal if <tt>x.equals(y)</tt>. (Note that this * definition is recursive for annotation typed members.) * * <li>Two corresponding array typed members <tt>x</tt> and <tt>y</tt> * are considered equal if <tt>Arrays.equals(x, y)</tt>, for the * appropriate overloading of {@link java.util.Arrays#equals}. * </ul> * * @return true if the specified object represents an annotation * that is logically equivalent to this one, otherwise false */
    boolean equals(Object obj);

    /** * Returns the hash code of this annotation, as defined below: * * <p>The hash code of an annotation is the sum of the hash codes * of its members (including those with default values), as defined * below: * * The hash code of an annotation member is (127 times the hash code * of the member-name as computed by {@link String#hashCode()}) XOR * the hash code of the member-value, as defined below: * * <p>The hash code of a member-value depends on its type: * <ul> * <li>The hash code of a primitive value <tt><i>v</i></tt> is equal to * <tt><i>WrapperType</i>.valueOf(<i>v</i>).hashCode()</tt>, where * <tt><i>WrapperType</i></tt> is the wrapper type corresponding * to the primitive type of <tt><i>v</i></tt> ({@link Byte}, * {@link Character}, {@link Double}, {@link Float}, {@link Integer}, * {@link Long}, {@link Short}, or {@link Boolean}). * * <li>The hash code of a string, enum, class, or annotation member-value I <tt><i>v</i></tt> is computed as by calling * <tt><i>v</i>.hashCode()</tt>. (In the case of annotation * member values, this is a recursive definition.) * * <li>The hash code of an array member-value is computed by calling * the appropriate overloading of * {@link java.util.Arrays#hashCode(long[]) Arrays.hashCode} * on the value. (There is one overloading for each primitive * type, and one for object reference types.) * </ul> * * @return the hash code of this annotation */
    int hashCode();

    /** * Returns a string representation of this annotation. The details * of the representation are implementation-dependent, but the following * may be regarded as typical: * <pre> * &#064;com.acme.util.Name(first=Alfred, middle=E., last=Neuman) * </pre> * * @return a string representation of this annotation */
    String toString();

    /** * Returns the annotation type of this annotation. * @return the annotation type of this annotation */
    Class<? extends Annotation> annotationType();
}

Yuan notes

Annotation classes that annotate annotation types , It is called meta annotation (meta-annotation).

@Target(ElementType.TYPE)
public @interface MyAnnotation {
    
    // TODO: 12/16/21 do something

}

annotation Target For custom annotations MyAnnotation A meta annotation of .

Classification of meta annotations

  • @Documented Used to be javadoc Tools to extract documents
  • @Inherited Indicates that subclasses are allowed to inherit annotations defined in the parent class
  • @Target Indicates that the marked annotation is in Java Scope of use in common classes
  • @Retention Specifies how the marked annotation is stored

In general , When customizing annotations , The meta annotation to be specified is @Target and @Retention.

@Target

/* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */

package java.lang.annotation;

/** * Indicates the contexts in which an annotation type is applicable. The * declaration contexts and type contexts in which an annotation type may be * applicable are specified in JLS 9.6.4.1, and denoted in source code by enum * constants of {@link ElementType java.lang.annotation.ElementType}. * * <p>If an {@code @Target} meta-annotation is not present on an annotation type * {@code T} , then an annotation of type {@code T} may be written as a * modifier for any declaration except a type parameter declaration. * * <p>If an {@code @Target} meta-annotation is present, the compiler will enforce * the usage restrictions indicated by {@code ElementType} * enum constants, in line with JLS 9.7.4. * * <p>For example, this {@code @Target} meta-annotation indicates that the * declared type is itself a meta-annotation type. It can only be used on * annotation type declarations: * <pre> * &#064;Target(ElementType.ANNOTATION_TYPE) * public &#064;interface MetaAnnotationType { * ... * } * </pre> * * <p>This {@code @Target} meta-annotation indicates that the declared type is * intended solely for use as a member type in complex annotation type * declarations. It cannot be used to annotate anything directly: * <pre> * &#064;Target({}) * public &#064;interface MemberType { * ... * } * </pre> * * <p>It is a compile-time error for a single {@code ElementType} constant to * appear more than once in an {@code @Target} annotation. For example, the * following {@code @Target} meta-annotation is illegal: * <pre> * &#064;Target({ElementType.FIELD, ElementType.METHOD, ElementType.FIELD}) * public &#064;interface Bogus { * ... * } * </pre> * * @since 1.5 * @jls 9.6.4.1 @Target * @jls 9.7.4 Where Annotations May Appear */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    
    /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */
    ElementType[] value();
}

ElementType The element type has the following values :

/* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */

package java.lang.annotation;

/** * The constants of this enumerated type provide a simple classification of the * syntactic locations where annotations may appear in a Java program. These * constants are used in {@link Target java.lang.annotation.Target} * meta-annotations to specify where it is legal to write annotations of a * given type. * * <p>The syntactic locations where annotations may appear are split into * <em>declaration contexts</em> , where annotations apply to declarations, and * <em>type contexts</em> , where annotations apply to types used in * declarations and expressions. * * <p>The constants {@link #ANNOTATION_TYPE} , {@link #CONSTRUCTOR} , {@link * #FIELD} , {@link #LOCAL_VARIABLE} , {@link #METHOD} , {@link #PACKAGE} , * {@link #PARAMETER} , {@link #TYPE} , and {@link #TYPE_PARAMETER} correspond * to the declaration contexts in JLS 9.6.4.1. * * <p>For example, an annotation whose type is meta-annotated with * {@code @Target(ElementType.FIELD)} may only be written as a modifier for a * field declaration. * * <p>The constant {@link #TYPE_USE} corresponds to the 15 type contexts in JLS * 4.11, as well as to two declaration contexts: type declarations (including * annotation type declarations) and type parameter declarations. * * <p>For example, an annotation whose type is meta-annotated with * {@code @Target(ElementType.TYPE_USE)} may be written on the type of a field * (or within the type of the field, if it is a nested, parameterized, or array * type), and may also appear as a modifier for, say, a class declaration. * * <p>The {@code TYPE_USE} constant includes type declarations and type * parameter declarations as a convenience for designers of type checkers which * give semantics to annotation types. For example, if the annotation type * {@code NonNull} is meta-annotated with * {@code @Target(ElementType.TYPE_USE)}, then {@code @NonNull} * {@code class C {...}} could be treated by a type checker as indicating that * all variables of class {@code C} are non-null, while still allowing * variables of other classes to be non-null or not non-null based on whether * {@code @NonNull} appears at the variable's declaration. * * @author Joshua Bloch * @since 1.5 * @jls 9.6.4.1 @Target * @jls 4.1 The Kinds of Types and Values */
public enum ElementType {
    
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /** * Type parameter declaration * * @since 1.8 */
    TYPE_PARAMETER,

    /** * Use of a type * * @since 1.8 */
    TYPE_USE
}

  • TYPE Indicates that the marked annotation can be applied to the class
  • FIELD Indicates that the marked annotation can be applied to the field or attribute of the class
  • METHOD Indicates that the marked annotation can be applied to the method of the class
  • PARAMETER Indicates that the marked annotation can be applied to the parameters of the method
  • CONSTRUCTOR Indicates that the marked annotation can be applied to the constructor
  • LOCAL_VARIABLE Indicates that the marked annotation can be applied to local variables of the class
  • ANNOTATION_TYPE Indicates that the marked annotation can be applied to the annotation type
  • PACKAGE Indicates that the marked annotation can be applied to the package declaration
  • TYPE_PARAMETER Indicates that the marked annotation can be applied to the declaration of type parameters
@Target({
    ElementType.TYPE,ElementType.FIELD})
public @interface MyAnnotation {
    
    // TODO: 12/16/21 do something

}

@MyAnnotation
public class MainActivity extends AppCompatActivity {
    

    @MyAnnotation
    private String value1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public static void main(String[] args) {
    

    }
}

@Retention

/* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */

package java.lang.annotation;

/** * Indicates how long annotations with the annotated type are to * be retained. If no Retention annotation is present on * an annotation type declaration, the retention policy defaults to * {@code RetentionPolicy.CLASS}. * * <p>A Retention meta-annotation has effect only if the * meta-annotated type is used directly for annotation. It has no * effect if the meta-annotated type is used as a member type in * another annotation type. * * @author Joshua Bloch * @since 1.5 * @jls 9.6.3.2 @Retention */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    
    /** * Returns the retention policy. * @return the retention policy */
    RetentionPolicy value();
}

RetentionPolicy There are the following values :

/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */

package java.lang.annotation;

/** * Annotation retention policy. The constants of this enumerated type * describe the various policies for retaining annotations. They are used * in conjunction with the {@link Retention} meta-annotation type to specify * how long annotations are to be retained. * * @author Joshua Bloch * @since 1.5 */
public enum RetentionPolicy {
    
    /** * Annotations are to be discarded by the compiler. */
    SOURCE,

    /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */
    CLASS,

    /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */
    RUNTIME
}

  • SOURCE Indicates that the marked annotation remains in the source code , The compiler will ignore .
  • CLASS Indicates that the marked annotation is retained by the compiler at compile time , but JVM Will ignore .
  • RUNTIME Indicates that the marked annotation is made by JVM Retain , In the runtime environment, you can use .
@Target({
    ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    
    // TODO: 12/16/21 do something

}

Annotation type elements

Customize the elements in the annotation .

When using annotations , Allow parameters to be passed .

@Target({
    ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    
    /** *  Element definition without default value  */
    String value();

    /** *  Element definitions with default values  */
    int id() default 0;
}

When using annotations , Attention should be paid to :

  • Element has no default value , When using annotations , It must be assigned a value .
  • When the element has a default value , According to need , It can be reassigned .
  • Only value Element time , The assignment method of key value pairs can be omitted .
@MyAnnotation("value")
public class MainActivity extends AppCompatActivity {
    

    @MyAnnotation(value = "value2", id = 1)
    private String value1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public static void main(String[] args) {
    

    }
}

Application scenarios for annotations

According to meta annotation @Retention Defined storage method , Annotations can be divided into three application scenarios :

  • SOURCE Source level annotations , Apply to IDE Syntax check 、apt In technology .
  • CLASS Level annotation , Annotations are retained in .class In file , But not by JVM Record , The corresponding is javac Command generated .class Bytecode file , Therefore, it is applied to the operation of bytecode , Modify bytecode directly class The file achieves the operation of modifying the logic related to the code , It is widely used in thermal repair technology .
  • RUNTIME Annotations are retained until runtime , The information in the annotation can be obtained in combination with reflection technology .

Previous articles are recommended

Growth path - Android Mobile development architect
Interview treasure - You're only one step away from a promotion and a raise
Brother Kun's Essays - There is always a dream , What if it does

Android Common open source libraries
Android Develop knowledge 、 Share

APP Architecture building - MVP Basic Edition
Blog knowledge system - Fundamentals of software development

Personal independent blog https://karenchia.gitee.io

 Insert picture description here

copyright notice
author[KarenChia],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270209006099.html

Random recommended