Learn to use Java annotations to define the value of the parameter

Foreword

  In Java development, we often need to enter the values ​​of some int or String type, and these values ​​may only be used on behalf of the state or category. However, we only want to input values ​​range from 0 to 5. This value of this parameter, if multiple input our big these operating code is not greater than the values ​​defined. So we need to limit. Under normal circumstances we can use the enumeration enum. However, individuals often toss Android development, and Android is not recommended to use enum, are particularly vulnerable because the activity is held causes a memory leak. So, we can only refer to a number of limited value annotation style.

Code section

Mode 1:

  More recommended to use this way

  First, create an interface to set some constants, we will only use this interface defines where the value:

public interface Level {
    int LEVEL_V = 1;
    int LEVEL_D = 2;
    int LEVEL_I = 3;
    int LEVEL_W = 4;
    int LEVEL_E = 5;
}

  Then create annotation classes, use @IntDef

// @Retention this annotation indicates a range of reservations, SOURCE = annotation will be discarded when the compiler, the presence of the code is not running, the annotation just want IDE warning range limit does not need to retain the running VM or 
@Retention (the SOURCE) 
 // @Target place the annotations need to use pARAMETER = annotations to be used to process parameters 
@Target ({pARAMETER}) 
 // integer value declared explicitly defined, except that there @LongDef @ @IntDef StringDef etc. 
@IntDef (value = {Level.LEVEL_V, Level.LEVEL_D, Level.LEVEL_I, Level.LEVEL_W, Level.LEVEL_E}) 
 public @ interface the LogLevel { 

}

  Then use this annotation we created LogLevel

public void setLogLevel(@LogLevel int level){
        this.level = level;
}

  Then we look at the results, just enter an integer value here, you can see Android studio has been warned, we can only choose to tell the following values.

  After entering the correct no warning prompt.

Option 2:

  This is an easier way to violence, write notes directly in the constant, because annotation class itself is actually an interface. Then declare your own constant

@Retention(SOURCE) 
@Target({PARAMETER})
@IntDef(value = {LogLevel.LEVEL_V, LogLevel.LEVEL_D, LogLevel.LEVEL_I, LogLevel.LEVEL_W, LogLevel.LEVEL_E})
public @interface LogLevel {
    int LEVEL_V = 1;
    int LEVEL_D = 2;
    int LEVEL_I = 3;
    int LEVEL_W = 4;
    int LEVEL_E = 5;

}

 

end

Guess you like

Origin www.cnblogs.com/guanxinjing/p/12162036.html