preface

  • inJavaAnnotations are very important, but for many developers, they are not easy to understand or even a little mysterious
  • Today, I will offer oneJavaIntroduction of notes & combat walkthroughsI hope you like it.



directory


1. Introduction

  • Definition: an identity/label


    1. Annotations belongs toJavaOf the same kindclassAnd the interfaceinterfaceThe same

    2. inJava SE 5.0Began to introduce
    3. Basic function: identification/interpretationJavacode



2. Application scenarios

  • For compiler/APT use

    1. APT (Annotation Processing Tool): Extraction & processingAnnotationThe code of
    2. Because when developers useAnnotationAfter modifying members of classes, methods, methods, etc., theseAnnotationDoes not take effect by itself, the developer must provide the corresponding code to extract and processAnnotationInformation. These processes are extracted and processedAnnotationCollectively referred to asAPT
  • So, in addition to explaining the basic code, the context of the annotation also depends on how you want to use it

  • Here are some typical application scenarios:

Scenario 1: Test the code

For example, the well-known testing framework JUnit = uses annotations for code testing

public class ExampleUnitTest { @Test public void Method() throws Exception { ... }} // @test marks the Method to be tested.Copy the code

Scenario 2: Simplify usage & reduce code

For example, Http network request library Retrofit & IOC framework ButterKnife

Public interface GetRequest_Interface {@get ("ajax.php? a=fy&f=auto&t=auto&w=hello%20world") Call<Translation> getCall(); } <-- IOC framework ButterKnife --> public class MainActivity extends AppCompatActivity {// Set resources @bindView (R.i.D.test) via annotations. TextView mTv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); }}Copy the code

3. Type of annotations

Types of annotations include: meta annotations, Java built-in annotations & custom annotations.

3.1 yuan notes

3.1.1 profile
  • Definition: an identity/label


    Is a basic annotation =
    AndroidBuilt-in system annotations

  • Purpose: Identifies/interprets developer custom annotations
3.1.2 The relationship between annotations, meta-annotations and Java code
  • Meta-annotations act on annotations & explain annotations
Public @interface Carson_Annotation {} public @interface Carson_Annotation {}Copy the code
  • Annotation onJavaCode & ExplanationJavacode
@carson_annotation public class Carson {}Copy the code
3.1.3 Introduction to meta-annotation types
  • There are five types of meta-annotations, including:

  • I will introduce them one by one

@Retention

  • Definition: Keep annotations
  • Purpose: explains/illustrates the life cycle of annotations
  • The specific use
// Meta annotation @Retention(retentionPolicy.runtime) Note The lifecycle of a Carson_Annotation = retained until the program is run & loaded into the JVM @Retention(retentionPolicy.runtime) public @interface Carson_Annotation {} <-- @retention parameter Description --> // retentionPolicy.runtime: // retentionPolicy. CLASS: Annotations are only reserved until compile time & not loaded into the JVM // retentionPolicy. SOURCE: Annotations are only retained at the source stage & are discarded and ignored when the compiler compiles.Copy the code

@Documented

  • Definition:JavaThe document notes
  • Purpose: To include elements in the annotation toJavadocIn the document
  • The specific use
@documented Public @interface Carson_Annotation {}Copy the code

@Target

  • Definition: Target annotations
  • Scope: defines the scope of the annotation scope, including classes, methods, and so on
  • The specific use
// @target: @target (ElementType.METHOD) public @interface Carson_Annotation {} <-- @target value parameter Description --> // ElementType.PACKAGE: ElementType. // ElementType.TYPE: You can annotate a TYPE, such as a class, interface, or enumeration.CONSTRUCTOR: You can annotate a CONSTRUCTOR. PARAMETER Can be used to annotate parameters within a method // elementType. FIELD: can be used to annotate attributes // elementType. LOCAL_VARIABLE: Local variables can be annotatedCopy the code

@Inherited

  • Definition: Inherit annotations
  • Function: to make aAnnotations annotated by @InheritedA class’s subclasses can inherit annotations from that class


    1. Prerequisite: Subclasses are not applied by any annotations
    2. For example, annotations@Carson_Annotation(Metaannotated@InheritedAnnotation) applies to class A, then A subclass of class A inherits the annotation of class A
    3. The specific use


// Inherited annotation @inherited public @interface Carson_Annotation {} // Carson_Annotation applies to class A @carson_annotation public class A {} // Class B inherits class A, i.e. class B = A subclass of class A, Carson_Annotation public class B extends A {} Carson_Annotation public class B extends A {}Copy the code

@Repeatable

  • Definition: repeatable annotations


    Java1.8 after the introduction of

  • Effect: Enables the annotation to take more than one value
  • The specific use
@job public @interface Job {Person[] value(); } <-- container annotation introduction --> // definition: is an annotation itself // function: store other annotations // specific use: must have a value attribute; Type = array of annotations annotated by @REPEATable // in this case, by @REPEATable = @person, so value property = Person [] array // 2. @person // 3. Use @repeatable @person // @repeatable (job.class) public @interface Person{String role default ""; }} @person (annotated by @REPEATable) can take multiple values to interpret Java code. @person (role="coder") @person (role="PM") public class Carson{}Copy the code
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Carson_Annotation {
}Copy the code
3.1.4 Summary of meta-annotation types

3.2 Java built-in annotations

  • Definition: annotations that are already implemented in Java
  • Type:JavaThere are five classes of built-in annotations, including:

  • I’ll explain the five types of built-in annotations below

@Deprecated

  • Definition: Obsolete annotations
  • Function: Marks obsolete & discarded elements (classes, methods, etc.)
  • The specific use
Public class Buyer2 {@deprecated public void Hello(){system.out.println ("Hello 2015!" ); }}Copy the code

When using a method in this class that is Deprecated by @deprecated, the IDE will indicate that the method is obsolete/Deprecated

@Override

  • Definition: Duplicate notes
  • Effect: Flags that this method needs to be overridden by subclasses
  • Specific use: this method is very familiar, not too much description here

@SuppressWarnings

  • Definition: Block warning annotations
  • What it does: The element of the tag prevents the compiler from issuing a warning


    This is mainly used when developers need to ignore warnings

  • The specific use
@suppressWarnings ("deprecation") public void test(){Buyer2 mBuyer2 = new Buyer2(); MBuyer2. Hello (); // the IDE will not issue a warning (that is, will not underline hello ())}Copy the code

@SafeVarargs

  • Definition: Parameter safety type annotation


    Java1.7 after the introduction of

  • Purpose: To remind developers not to use arguments to do unsafe operations & prevent compiler generationuncheckedwarning
  • The specific use
ClassCastException is thrown at runtime, although no errors are reported at compile time. SafeVarargs // Not actually Safe! static void m(List<String>... stringLists) { Object[] array = stringLists; List<Integer> tmpList = Arrays.asList(42); array[0] = tmpList; // Semantically invalid, but compiles without warnings String s = stringLists[0].get(0); // Oh no, ClassCastException at runtime! }Copy the code

@FunctionalInterface

  • Definition: functional interface annotations

    New features introduced after Java 1.8

  • Function: Indicates that the interface is a functional interface

    Functional Interface = 1 plain Interface with 1 method

  • The specific use

@functionalInterface public interface Runnable {public abstract void run(); } <-- additional: why use functional interface notation --> // Reason: Functional interfaces can easily be converted to Lambda expressions // This is another big topic, which I won't go into too much hereCopy the code

Summary of Java built-in annotation types


3.3 Customizing Annotations

  • Definition: developer custom annotations
  • Specific uses: This is described in section 4 below.

4. Introduction to usage

The basic uses of annotations include definitions, attributes & specific uses

4.1 Definition of annotations

// defined by the @interface keyword // in the form of an interface, Public @interface Carson_Annotation {} // The above code creates an annotation called Carson_AnnotaionCopy the code

4.2 Attributes of annotations

Public @interface Carson_Annotation {// Attributes of annotations = member variables // Annotations only have member variables, No method // annotation @carson_annotation has 2 properties: id and MSG int ID (); String msg() default "Hi" ; / / description: // Attribute name = attribute name // method return value = attribute type = 8 basic data types + class, interface, annotation and corresponding array type // Specify the default attribute value with the default key value. The default value of MSG above = "Hi"} <-- 2. Annotate attribute assignment --> // Annotate attribute assignment when used // Annotate attribute assignment method = annotation parenthesis "value=" xx ""; Use ", Carson_Annotation(id=1, MSG =" Hello, I am Carson") public class @carson_annotation (id=1, MSG =" Hello, I am Carson") public class A {} // Special note: If the annotation has only one attribute, @carson_annotation ("hello, I am Carson") public class A {@carson_annotation (" Hello, I am Carson") public class A { }Copy the code

4.3 Application of annotations

@carson_annotation public class Carson {@carson_annotation int a; @carson_annotation int a; @carson_annotation public void bMethod(){}} @carson_annotation is used to define the Carson class/a variable/b methodCopy the code

4.4 Obtaining Annotations

  • Definition: To get all annotations on an object.
  • Means of implementation:JavaReflection technology


    Due to the high time cost of reflection, annotations should be used with caution

  • The specific use
< - step 1: determine whether the application a certain annotations - > / / methods: USES the Class. IsAnnotationPresent () public Boolean isAnnotationPresent (Class <? Extends Annotation> annotationClass) {} <-- step 2: getAnnotation --> getAnnotation(); Returns annotations of the specified type public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {} Public Annotation[] getanannotations () {} returns all annotations on this element.Copy the code
  • Below I will use an example to show how to get an annotation type on a class, method & member variable

Step 1: Customize 2 annotations

Carson_Annotation.java

// Because @carson_annotation needs to be used at RUNTIME, meta-annotation @Retention(retentionPolicy.runtime) @retention (retentionPolicy.runtime) must be used Public @interface Carson_Annotation {// annotation @carson_annotation has two attributes: id and MSG int ID (); String msg() default "Hi"; }Copy the code

Carson_Annotation2.java

// The annotation @carson_annotation2 needs to be used when the program is run. Therefore, the annotation @annotation (retentionPolicy.runtime) is required for Retention(retentionPolicy.runtime). Public @carson_annotation2 {// annotation @carson_annotation2 has two attributes: id and MSG int id(); String msg() default "Hi"; }Copy the code

Step 2: Define an annotated class

Test.java

@carson_annotation (id = 1, MSG =" I am class Test") public class Test {@carson_annotation (id = 1, MSG =" I am class Test") public class Test If (1, MSG =" I am a variable ") int a; @carson_annotation (id = 3, MSG =" I am annotation b") @carson_annotation (id = 4, MSG =" I am annotation BB (from annotation 2) ") public void bMethod(){} }Copy the code

Step 3: Get an annotation on a class, a method, and a member variable

private static final String TAG = "Annotation"; /** * 1: @carson_annotation Boolean hasAnnotation = Test.class.isAnnotationPresent(Carson_Annotation.class); If (hasAnnotation) {Carson_Annotation classAnnotation = // 2. If (hasAnnotation) {Carson_Annotation classAnnotation = // 2 Test.class.getAnnotation(Carson_Annotation.class); // 3. Get the value of the annotation object log. d(TAG, "I am the annotation on the Test class "); Log.d(TAG, "id:" + classAnnotation.id()); Log.d(TAG, "msg:" + classAnnotation.msg()); } /** * note 2: Get the annotation on class member a */ try {// 1. Access to the members of the class variables a Field a = Test. Class. GetDeclaredField (" a "); a.setAccessible(true); @carson_annotation Carson_Annotation variableAnnotation = A.goetAnnotation (Carson_annotation.class); If (variableAnnotation = true) {// If (variableAnnotation = true) {// If (variableAnnotation! = null) {log. d(TAG, "I am an annotation on class member variable A "); Log.d(TAG, "id:" + variableAnnotation.id()); Log.d(TAG, "msg:" + variableAnnotation.msg()); } / * * * on 3: get class methods bMethod comment * / / / 1. For class methods bMethod Method testMethod = Test. Class. GetDeclaredMethod (" bMethod "); If (testMethod! = null) {/ / because there are two methods, so the getAnnotations () to obtain all types of annotations Annotation [] ans = testMethod. GetAnnotations (); Log.d(TAG, "I'm an annotation for class method bMethod "); For (int I = 0; i < ans.length ; I ++) {log.d (TAG, "class method "+" annotation "+ I + ans[I].annotationType().getSimplename ()); } } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); }}Copy the code
  • The test results

  • The Demo address

Carson’s Github address: Java_Annotation


5. Practice

Next, I’ll use annotations to implement one of the most common application scenarios: test code

5.1 Example Description

Annotations are used to check for exceptions to methods in a class

5.2 Procedure

  • Step 1: Customize test annotations

Carson_Test.java

@retention (retentionPolicy.runtime) @retention (retentionPolicy.runtime) public is required because the @carson_test annotation needs to be used when the program is run @interface Carson_Test { }Copy the code
  • Step 2: Define the classes you want to test

Test.java

Public class Test {@carson_test public void method1(){system.out.println ("method1 normal = "+ (1+1)); } @carson_test public void method2(){system.out.println ("method2 works = "+ (2*3)); } @carson_test public void method3(){system.out.println ("method3 works = "+ (2/0));} @carson_test public void method3(){system.out.println ("method3 works =" + (2/0)); }}Copy the code
  • Step 3: Test the existence of the class’s methods with annotationsBug

MainActivity.java

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Test mTest = new Test(); Class mTest_Class = mTest.getClass(); [] Method = mtest_class.getDeclaredMethods (); // 3. Test a method in a class by annotating @carson_test. For (Method m: Method) {// b. If (m.isanNotationPresent (carson_test.class)) {try {m.setaccessible (true); if (m.isanNotationPresent (carson_test.class)) {try {m.setaccessible (true); // c. Call the test class method m.invoke(mTest) by reflection; } catch (Exception e) {system.out.println ("Test class has a Bug!!" ); System.out.println(" buggy method: "+ m.goetname ()); System.out.println("Bug type: "+ LLDB ().getClass().getSimplename ()); System.out.println("Bug message: "+ LLDB ().getMessage()); }}}}Copy the code

5.3 Test Results

5.4 Demo address

Carson_Ho Github address: Annation_Debug


6. Summary

  • This article is a comprehensive explanation of Java annotations, I believe you have a deep understanding of Java annotations.

  • I’m going to continue to talk about Android in more depth. If you’re interested, please stay tuned for Carson_Ho’s Android development notes


Please give the top/comment a thumbs up! Because your encouragement is the biggest power that I write!