Common annotations provided by Android and custom annotations instead of enumerations

Source: Internet
Author: User

Respect for the work of others, reproduced please indicate the source: http://blog.csdn.net/gengqiquan/article/details/70185731, this article from: "Gengqiquan blog"

The previous blog muttered the basics of annotations. This and everybody's chatter about some of the compilation restrictions that Android offers and how to customize the limitations of the framework for your own project

Android supports Java default annotations, and with some additional annotations through some dependent libraries, understanding and familiarity with these annotations can make your code more rigorous, more structured, and easier to maintain.

The Android Support Library has introduced a new annotation library from version 19.1 support Annotations
Support APPCOMPA-V7 contains this library by default, and if you don't use it, you can introduce it by adding a separate dependency.
In the model Build.gradle, add the following configuration:

{    compile ‘com.android.support:support-annotations:25.2.0‘}

The selected version of 25.2.0 contains the following types of annotations

    • Resource reference restriction Class: Used to restrict the parameter must be the corresponding resource type

      Animres anyres arrayres attrres boolres colorres dimenres drawableres fractionres idres IntegerRes InterpolatorRes LayoutR Es menures pluralsres Px rawres stringres styleableres styleres transitionres xmlres

    • Thread execution restriction class: Used to restrict the method or the class must execute on the specified thread

      Anythread binderthread mainthread Uithread workerthread

    • Parameter nullability restriction class: Used to limit whether a parameter can be empty

      Nonnull Nullable

    • Type range restriction class: The range of values used to limit dimension values

      Floatrang Intrange

    • Type definition class: A collection of values used to restrict the definition of annotations

      Intdef Stringdef

    • Other functional annotations:

      Callsuper checkresult colorint Dimension Keep Px requiresapi requirespermission restrictto Size visiblefortesting

Below are examples of how to use

Resource reference restriction classes

Used to add the corresponding resource type annotation when we expect the input to be the corresponding type for the annotation. This will cause the compiler to make an error if the resource ID of the non-expected type is entered, for example, when we write the project framework, we define an abstract method that sets the main layout, which requires the subclass to inherit the class to implement this method, and return a layout ID, which we would normally write.

    publicabstractintgetLayoutID();

This limits the data type that is returned to an int. If the person implementing the class wears a drawable ID or an int value, it can be compiled normally. The error will not be reached until the interface is run. At this point, we can annotate the method with the annotations provided by the support annotations package.

    @LayoutRes    publicabstractintgetLayoutID();

This way, when the person implementing the class passes in a non-layout ID, the compiler will report except resource of type layout exception and cause it to fail to compile.

Thread execution Throttling classes

In our code, it is a good habit to extract code as a standalone method, not only for code reading and multiple invocations of the same logic, but also for later refactoring, while extracting the code allows you to think about whether the logical implementation is too bloated. But the extracted method may be placed in the activity of the writing may also be placed in the public class or into a static method, at this time you can not guarantee to know where the caller will use your code.

Unless he takes the time to read your code carefully, he will not know how many methods have been called in the method he called, such as the code that contains some IO operations, or the way the method executes is particularly time-consuming to call on a child thread. Or the method inside the UI must be called in the main thread. At this point, you can use the thread to execute the restriction class annotations on your method, the compiler will make an error when the caller does not call this method in the thread you expect.

It is important to note that the scopes of these annotations are classes and methods. When labeling a class, it indicates that the class and the internal method must be executed on the specified thread, including the constructor method.
For example, the View interface method in MVP

publicinterface IBaseView {    @UiThread    void showLoading();    }

The load box must be called in the UI thread

parameter is nullability restricted class

This is relatively simple, people in the implementation of the Android SDK method can often be overridden in the system method when you encounter

When the nonnull is labeled on a parameter, the compiler checks to see if the parameter field may be empty, and when marked on the method, checks whether the returned value is empty. May be empty when the compiler prompts you for a potential crash hazard

Nullable is labeled on a parameter or method with a return value, indicating that the parameter or method return value can be null

Type restriction class

Restricting the data type of a parameter

Floatrange qualified Annotated object must be float or double

@Retention(CLASS)@Target({Method,parameter,field,local_variable,annotation_type}) Public@ interface floatrange {    //Start value    DoubleFrom ()defaultdouble.negative_infinity;//End value    Doubleto ()defaultdouble.positive_infinity;//Whether the start value is included    BooleanFrominclusive ()default true;//Whether the end value is included    BooleanToinclusive ()default true;}

Intrange qualified annotated object must be int or long

@Retention(CLASS)@Target({METHOD,PARAMETER,FIELD,LOCAL_VARIABLE,ANNOTATION_TYPE})public @interface IntRange {    //起始值,包含起始值    longfromdefault Long.MIN_VALUE;    //终点值,包含终点值    longdefault Long.MAX_VALUE;}
Type definition Class

Typically used instead of enumerations, when we define an API, we sometimes need to pass in some locally defined values. In order to make these values readable we will choose to use static constants, and sometimes we need to limit the set of desirable parameters. These types of merit may be the underlying data type. In order to avoid invoking the API by the person passing in other non-expected unexpected values come in, we will often choose to use enumerations. Enumerations are more expensive to perform. At this point, we can use annotations to replace
For example, we have an API for uploading images. Upload type needs to choose JPG or PNG, the way to enumerate is relatively simple. Directly define a picture type enumeration

publicenum  ImgType {    jpg,png;}

Api

publicvoid  uploadImg(ImgType type) {}

You are now using annotations to implement this requirement.
Let's first define two int constants and put them in a constant class data.

publicclass   Data {   publicstaticfinalint JPG=1000;   publicstaticfinalint PNG=1001;}

Then we define a imgtype annotation

@IntDef({Data.JPG,Data.PNG})@Retention(RetentionPolicy.SOURCE)public @interface ImgType {}

So we define a compile-time check, and we put this annotation on the type parameter of the API that uploads the image.

publicvoid  uploadImgint type) {}

So when we call the API, once we pass in the parameter is not data.jpg or data.png, the compiler will error can not be compiled

Stringdef usage is similar

Other functional classes

Callsuper If your API allows the user to rewrite your method, but you need your own method (the parent method) is also called when rewriting, you can use the @callsuper annotation

Checkresult If your method returns a value and you expect the caller to do something with that value, you can use the @checkresult annotation to annotate the method, which is typically used for APIs where the return value is used to make sense.

Colorint when you expect to pass a real RGB or ARGB color value instead of a color resource ID, you can use that annotation to prompt the API caller

Dimension the object or method to be labeled must provide an int value, which is a unit of distance on the Android screen

Keep when confusing is enabled tell the compiler that the object being annotated does not confuse

The object or method of the Px callout must provide the value of an int, pixel

REQUIRESAPI when you provide an API that is based on an SDK version, the caller must handle the Low SDK version compatibility operation, or tell the caller that your API can only work properly after a certain version of the SDK

Requirespermission tells the person calling your API that your API requires specific permissions
If you need at least one of the permission sets, you can use the Anyof property

@RequiresPermission(anyOf = {    Manifest.permission.INTERNET,    Manifest.permission.READ_PHONE_STATE})publicabstractstringgetSaveUser();

If you need multiple permissions at the same time, you can use the AllOf property

@RequiresPermission(allOf = {    Manifest.permission.READ_PHONE_STATE,    Manifest.permission.READ_PHONE_STATE})publicabstractstringgetSaveUser();

Restrictto Annotated objects accept only a specific range of values, and the value range is an enumeration

Size Limits a collection of lists

 @Retention (Class) @Target ({parameter,local_variable,method, Field,annotation_type}) public  @interface  Size {//the note must be given a value, default-1  long  value  () default -1 ;    //the smallest size    long  min () default  long.min_value;    //maximum size     long  max () default  long.max_value;    //size must be a multiple of this value, default is 1  long  multiple () default  1 ;}  

Visiblefortesting can be called directly when the object is tested by this annotated function.

The above is the use of the annotations provided by support annotations, due to the length of the question, the next article we talk about how to define and code parsing runtime annotations

Do you have any suggestions to leave a message?

If my blog is helpful to you, please leave a message to encourage or click to praise it!

I built a QQ group (Group No.: 121606151), for everyone to discuss the exchange of Android technology issues, interested can add, we progress together.

Common annotations provided by Android and custom annotations instead of enumerations

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.