Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of Android annotations

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "what is the use of Android notes", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what is the use of Android notes" this article.

First of all, what are notes? @ Override is an annotation, and what it does is:

1. Check whether the methods in the parent class are overridden correctly.

2. Mark the code, which is a rewriting method.

1. Check whether the method name and parameter type overridden by the subclass are correct, and check that the method private/final/static cannot be overridden. In fact, @ Override has no actual impact on the application, which can be found in its source code.

2. It mainly shows the readability of the code.

As a well-known annotation in Android development, Override is only an embodiment of annotations, and more often, annotations have the following functions:

Reduce the coupling of the project.

Automatically complete some regular code.

Automatically generate java code to reduce the workload of developers.

1. Quick reading of the basis of annotations. 1. Meta notes

Meta-annotations are the basic annotations provided by java and are responsible for annotating other annotations. For example, the Override above is modified by @ Target and @ Retention, which are used to explain and explain other annotations and are located under the sdk/sources/android-25/java/lang/annotation path.

Meta notes are as follows:

@ Retention: the lifecycle of annotation retention

@ Target: annotate the scope of the object.

Inherited:@Inherited indicates whether the modified annotation can be inherited on the class it acts on.

Documented: as the name suggests, javadoc's tools are documented and generally don't care.

@ Retention

Retention says it indicates the life cycle of the annotations, which corresponds to the enumeration of RetentionPolicy, indicating when the annotations take effect:

SOURCE: valid only in source code, discarded at compile time, such as @ Override above.

CLASS: takes effect when compiling class files.

RUNTIME: takes effect only at run time.

As shown in the figure below, the Nullable comments in com.android.support:support-annotations will determine whether the annotated parameters will be empty during the compilation time.

@ Target

Target indicates the scope of application of annotations, corresponding to ElementType enumeration, and defines the valid scope of annotations.

TYPE: classes, interfaces, enumerations, annotation types.

FIELD: class members (constructors, methods, member variables).

METHOD: method.

PARAMETER: parameter.

CONSTRUCTOR: constructor.

LOCAL_VARIABLE: local variable.

ANNOTATION_TYPE: comments.

PACKAGE: package declaration.

TYPE_PARAMETER: type parameter.

TYPE_USE: type usage declaration.

As shown in the figure above, @ Nullable can be used to annotate methods, parameters, class members, annotations, and package declarations. Common examples are as follows:

/ * Nullable indicates that the parameter target and return value Data of * bind method can be null * / @ Nullable public static Data bind (@ Nullable Context target) {/ / do someThing and return return bindXXX (target);}

@ Inherited

The class on which the annotation operates cannot inherit the annotation of the parent class by default when inheriting. Unless the annotation declares @ Inherited. At the same time, the notes declared by Inherited are valid only for classes, not for methods / properties.

As in the following code, the annotation class @ AInherited declares Inherited, while the annotation BNotInherited does not, under their decorations:

Class Child inherits @ AInherited of parent class Parent, but does not inherit @ BNotInherited

The overridden method testOverride () does not inherit any comments from Parent

TestNotOverride () is still valid because it has not been rewritten.

Retention (RetentionPolicy.RUNTIME) @ Inherited public @ interface AInherited {String value ();} @ Retention (RetentionPolicy.RUNTIME) public @ interface BNotInherited {String value () } @ AInherited ("Inherited") @ BNotInherited ("no Inherited") public class Parent {@ AInherited ("Inherited") @ BNotInherited ("no Inherited") public void testOverride () {} @ AInherited ("Inherited") @ BNotInherited ("no Inherited") public void testNotOverride () {}} / * Child inherits Parent's AInherited note * BNotInherited because there is no @ Inherited declaration * /} 2. Custom comments

2.1 Runtime comments

Now that you know about meta-annotations, take a look at how to implement and use custom annotations. Here we briefly introduce the runtime annotation RUNTIME, while the compile-time annotation CLASS is left for later analysis.

First, create an annotation that follows: public @ interface annotation name {method parameter}, as shown below @ getViewTo annotation:

@ Target ({ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface getViewTo {int value () default-1;}

Then, as shown below, we describe the annotations in the member variables mTv and mBtn of Activity, and when App runs, the controls obtained by findViewbyId are injected into mTv and mBtn through reflection.

Isn't it familiar, a little bit like ButterKnife? Of course, ButterKnife is much more advanced than this, after all, more reflection affects efficiency, but we see that you can inject and create objects through annotations, which can save some amount of code.

Public class MainActivity extends AppCompatActivity {@ getViewTo (R.id.textview) private TextView mTv; @ getViewTo (R.id.button) private Button mBtn; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); / / generate View through annotations GetAllAnnotationView ();} / * parse the annotation, get the control * / private void getAllAnnotationView () {/ / get the member variable Field [] fields = this.getClass () .getDeclaredFields () / / findViewById injects the annotated id to find View into the member variable field.set (this, findViewById (getViewTo.value ();} catch (Exception e) {}

2.2 compile-time comments

Runtime annotations RUNTIME as shown above, most of the time the runtime uses reflection to achieve the desired effect, which greatly affects efficiency if each View injection of BufferKnife is not possible. In fact, ButterKnife uses the compile-time annotation CLASS, as shown in figure X2.2, which is the @ BindView annotation of ButterKnife, which is a compile-time annotation that generates the corresponding java code at compile time and implements the injection.

When it comes to compile-time annotations, we have to say that the annotation processor AbstractProcessor, if you have noticed, the general third-party annotation-related class libraries, such as bufferKnike, ARouter, all have a Module named by Compiler, as shown in figure X2.3 below, which are generally annotation processors that are used to process corresponding annotations at compile time.

The annotation processor (Annotation Processor) is a tool of javac that scans and processes annotations (Annotation) at compile time. You can customize comments and register the corresponding annotation processor to handle your annotation logic.

As shown below, implement a custom annotation handler, override at least four methods, and register your custom Processor. For details, please refer to the code CustomProcessor below.

@ AutoService (Processor.class), an automatic registration note provided by Google, generates the format files (com.google.auto related packages) needed to register Processor for you.

Init (ProcessingEnvironment env), initialize the processor, which is where we usually get the utility classes we need.

GetSupportedAnnotationTypes (), which specifies which annotation the annotation processor is registered with, and returns the specified collection of supported annotation classes.

GetSupportedSourceVersion (), which specifies the java version.

Process (), the processor actually handles the logic entry.

@ AutoService (Processor.class) public class CustomProcessor extends AbstractProcessor {/ * initialization of the annotation processor * generally get the utility classes we need here * @ param processingEnvironment provides tool classes Elements, Types and Filer * / @ Override public synchronized void init (ProcessingEnvironment env) {super.init (env); / / Element represents the elements of the program, such as packages, classes, and methods. MElementUtils = env.getElementUtils (); / / tool class dealing with TypeMirror, used to fetch class information mTypeUtils = env.getTypeUtils (); / / Filer can create a file mFiler = env.getFiler (); / / error handling tool mMessages = env.getMessager () } / * processor actual processing logic entry * @ param set * @ param roundEnvironment collection of all annotations * @ return * / @ Override public boolean process (Set

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report