1page.title=Improving Code Inspection with Annotations 2@jd:body 3 4<div id="qv-wrapper"> 5<div id="qv"> 6 7 <h2>In this document</h2> 8 <ol> 9 <li><a href="#adding-nullness">Adding Nullness Annotations</a></li> 10 <li><a href="#res-annotations">Adding Resource Annotations</a></li> 11 <li><a href="#thread-annotations">Adding Thread Annotations</a></li> 12 <li><a href="#value-constraint">Adding Value Constraint Annotations</a></li> 13 <li><a href="#permissions">Adding Permission Annotations</a></li> 14 <li><a href="#check-result">Adding CheckResult Annotations</a></li> 15 <li><a href="#call-super">Adding CallSuper Annotations</a></li> 16 <li><a href="#enum-annotations">Creating Enumerated Annotations</a></li> 17 </ol> 18 19 <h2>See also</h2> 20 <ol> 21 <li><a href="{@docRoot}tools/help/lint.html">lint (reference)</a></li> 22 <li><a href="{@docRoot}tools/debugging/improving-w-lint.html">Improving Your Code with lint</a></li> 23 <li><a href="{@docRoot}tools/studio/index.html#annotations">Annotations in Android Studio</a></li> 24 </ol> 25 26</div> 27</div> 28 29<p>Using code inspections tools such as <a href="{@docRoot}tools/help/lint.html">lint</a> can help 30you find problems and improve your code, but inspection tools can only infer so much. Android 31resource ids, for example, use an {@code int} to identify strings, graphics, colors and other 32resource types, so inspection tools cannot tell when you have specified a string resource where 33you should have specified a color. This situation means that your app may render incorrectly or 34fail to run at all, even if you use code inspection. </p> 35 36<p>Annotations allow you to provide hints to code inspections tools like {@code lint}, to help 37detect these, more subtle code problems. They are added as metadata tags that you attach to 38variables, parameters, and return values to inspect method return values, passed parameters, and 39local variables and fields. When used with code inspections tools, annotations can help you detect 40problems, such as null pointer exceptions and resource type 41conflicts. </p> 42 43<p>For more information on enabling <a href="{@docRoot}tools/help/lint.html">lint</a> inspections 44and running <a href="{@docRoot}tools/help/lint.html">lint</a>, 45see <a href="{@docRoot}tools/debugging/improving-w-lint.html">Improving Your Code with lint</a>.</p> 46 47<p>Android supports a variety of annotations for insertion in the methods, parameters, and return 48values in your code, for example:</p> 49 50<dl> 51 <dt>{@link android.support.annotation.Nullable @Nullable}</dt> 52 <dd>Can be null.</dd> 53 54 <dt>{@link android.support.annotation.NonNull @NonNull}</dt> 55 <dd>Cannot be null.</dd> 56 57 <dt>{@link android.support.annotation.StringRes @StringRes}</dt> 58 <dd>References a <a href="{@docRoot}reference/android/R.string.html"><code>R.string</code></a> 59 resource.</dd> 60 61 <dt>{@link android.support.annotation.DrawableRes @DrawableRes}</dt> 62 <dd>References a 63 <a href="{@docRoot}guide/topics/resources/drawable-resource.html"><code>Drawable</code></a> 64 resource. </dd> 65 66 <dt>{@link android.support.annotation.ColorRes @ColorRes}</dt> 67 <dd>References a <a href="{@docRoot}reference/android/graphics/Color.html"><code>Color</code></a> 68 resource. </dd> 69 70 <dt>{@link android.support.annotation.InterpolatorRes @InterpolatorRes}</dt> 71 <dd>References a 72 <a href="{@docRoot}reference/android/view/animation/Interpolator.html"><code>Interpolator</code></a> 73 resource. </dd> 74 75 <dt>{@link android.support.annotation.AnyRes @AnyRes}</dt> 76 <dd>References any type of <a href="{@docRoot}reference/android/R.html"><code>R.</code></a> 77 resource. </dd> 78 79 <dt><code>@UiThread</code></dt> 80 <dd>Calls from a UI 81 <a href="{@docRoot}guide/components/processes-and-threads.html">thread</a>. </dd> 82 </dl> 83 84<p>For a complete list of the supported annotations, either examine the contents of the 85{@link android.support.annotation Support-Annotations} library or use the 86auto-complete feature to display the available options for the <code>import 87android.support.annotation.</code> statement. The 88<a href="{@docRoot}tools/help/sdk-manager.html"> SDK Manager</a> packages the 89{@link android.support.annotation Support-Annotations} library in the Android Support Repository 90for use with Android Studio and in the Android 91<a href="{@docRoot}tools/support-library/index.html">Support Library</a> for use with other Android 92development tools.</p> 93 94 95<p>To add annotations to your code, first add a dependency to the 96{@link android.support.annotation Support-Annotations} library. In Android Studio, 97add the dependency using the <strong>File > Project Structure > Dependencies</strong> menu 98option or your <code>build.gradle</code> file. The following example shows how to add the 99{@link android.support.annotation Support-Annotations} library dependency in the 100<code>build.gradle</code> file: </p> 101 102<pre> 103dependencies { 104 compile 'com.android.support:support-annotations:22.2.0' 105} 106</pre> 107 108 109<p>The {@link android.support.annotation Support-Annotations} library is decorated with the 110supported annotations so using this library's methods and resources automatically checks the code 111for potential problems.</p> 112 113<p>If you include annotations in a library and use the 114<a href="{@docRoot}tools/building/plugin-for-gradle.html"><code>Android Plugin for Gradle</code></a> 115to build an Android ARchive (AAR) artifact of that library, the annotations are included as part 116of the artifact in XML format in the <code>annotations.zip</code> file. </p> 117 118<p>To start a code inspection from Android Studio, which includes validating annotations and 119automatic <a href="{@docRoot}tools/help/lint.html">lint</a> checking, select 120<strong>Analyze > Inspect Code</strong> from the menu options. Android Studio displays conflict 121messages throughout the code to indication annotation conflicts and suggest possible 122resolutions.</p> 123 124 125<h2 id="adding-nullness">Adding Nullness Annotations</h2> 126<p>Add {@link android.support.annotation.Nullable @Nullable} and 127{@link android.support.annotation.NonNull @NonNull} annotations to check 128the nullness of a given variable, parameter, or return value. For example, if a local variable 129that contains a null value is passed as a parameter to a method with the 130{@link android.support.annotation.NonNull @NonNull} annotation 131attached to that parameter, building the code generates a warning indicating a non-null conflict. </p> 132 133<p>This example attaches the {@link android.support.annotation.NonNull @NonNull} annotation to 134the <code>context</code> and <code>attrs</code> parameters to check that the passed parameter 135values are not null. </p> 136 137<pre> 138import android.support.annotation.NonNull; 139... 140 141 /** Add support for inflating the <fragment> tag. */ 142 @NonNull 143 @Override 144 public View onCreateView(String name, @NonNull Context context, 145 @NonNull AttributeSet attrs) { 146 ... 147 } 148... 149</pre> 150 151<p class="note"><strong>Note:</strong> Android Studio supports running a nullability analysis to 152automatically infer and insert nullness annotations in your code. For more information about 153inferring nullability in Android Studio, see 154<a href="{@docRoot}tools/studio/index.html#annotations">Annotations in Android Studio</a>. </p> 155 156 157<h2 id="res-annotations">Adding Resource Annotations</h2> 158<p>Validating resource types can be useful as Android references to resources, such as 159<a href="{@docRoot}guide/topics/resources/drawable-resource.html"><code>Drawables</code></a> and 160<a href="{@docRoot}reference/android/R.string.html"><code>R.string</code></a> resources, are 161passed as integers. Code that expects a parameter to reference a specific type of resource, for 162example <a href="{@docRoot}guide/topics/resources/drawable-resource.html"><code>Drawables</code></a>, 163can be passed the expected reference type of <code>int</code>, but actually reference a different 164type of resource, such as a <code>R.string</code></a> resource. </p> 165 166<p>For example, add {@link android.support.annotation.StringRes @StringRes} annotations to check 167that a resource parameter contains a 168<a href="{@docRoot}reference/android/R.string.html"><code>R.string</code></a> 169reference. During code inspection, the annotation generates a warning if a <code>R.string</code> 170reference is not passed in the parameter.</p> 171 172<p>This example attaches the {@link android.support.annotation.StringRes @StringRes} 173annotation to the <code>resId</code> parameter to validate that it is really a string resource. </p> 174 175<pre> 176import android.support.annotation.StringRes; 177... 178 public abstract void setTitle(@StringRes int resId); 179 ... 180</pre> 181 182 183<p>Annotations for the other resource types, such as 184{@link android.support.annotation.DrawableRes @DrawableRes}, 185{@link android.support.annotation.DimenRes @DimenRes}, 186{@link android.support.annotation.ColorRes @ColorRes}, and 187{@link android.support.annotation.InterpolatorRes @InterpolatorRes} can be added using 188the same annotation format and run during the code inspection. </p> 189 190 191 192 193<h2 id="thread-annotations">Adding Thread Annotations</h2> 194<p>Thread annotations check if a method is called from a specific type of 195<a href="{@docRoot}guide/components/processes-and-threads.html">thread</a>. The following thread 196annotations are supported: </p> 197<ul> 198 <li><code>@UiThread</code> </li> 199 <li><code>@MainThread</code> </li> 200 <li><code>@WorkerThread</code> </li> 201 <li><code>@BinderThread</code> 202</ul> 203 204<p class="note"><strong>Note:</strong> The <code>@MainThread</code> 205and the <code>@UiThread</code> annotations are interchangeable so 206methods calls from either thread type are allowed for these annotations. </p> 207 208 209<p>If all methods in a class share the same threading requirement, you can add a single 210<a href="{@docRoot}guide/components/processes-and-threads.html">thread</a> 211annotation to the class to verify that all methods in the class are called from the same type of 212<a href="{@docRoot}guide/components/processes-and-threads.html">thread</a>. </p> 213 214<p>A common use of the <a href="{@docRoot}guide/components/processes-and-threads.html">thread</a> 215annotation is to validate method overrides in the 216<a href="{@docRoot}reference/android/os/AsyncTask.html">AsyncTask</a> class as this class performs 217background operations and publishes results only on the UI 218<a href="{@docRoot}guide/components/processes-and-threads.html">thread</a>. </p> 219 220 221 222<h2 id="value-constraint">Adding Value Constraint Annotations</h2> 223<p>Use the <code>@IntRange</code>, 224<code>@FloatRange</code>, and 225<code>@Size</code> annotations to validate the values of passed 226parameters. </p> 227 228<p>The <code>@IntRange</code> annotation validates that the parameter 229value is within a specified range. The following example ensures that the <code>alpha</code> 230parameter contains an integer value from 0 to 255: </p> 231 232<pre> 233public void setAlpha(@IntRange(from=0,to=255) int alpha) { … } 234</pre> 235 236<p>The <code>@FloatRange</code> annotation checks that the parameter 237value is within a specified range of floating point values. The following example ensures that the 238<code>alpha</code> parameter contains a float value from 0.0 to 1.0: </p> 239 240<pre> 241public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {...} 242</pre> 243 244<p>The <code>@Size</code> annotation checks the size of a collection or 245array, as well as the length of a string. For example, use the <code>@Size(min=1)</code> 246annotation to check if a collection is not empty, and the <code>@Size(2)</code> annotation to 247validate that an array contains exactly two values. The following example ensures that the 248<code>location</code> array contains at least one element: </p> 249 250<pre> 251int[] location = new int[3]; 252button.getLocationOnScreen(@Size(min=1) location); 253</pre> 254 255 256<h2 id="permissions">Adding Permission Annotations</h2> 257<p>Use the <code>@RequiresPermission</code> annotation to 258validate the permissions of the caller of a method. To check for a single permission from a 259list the valid permissions, use the <code>anyOf</code> attribute. To check for a set of 260permissions, use the <code>allOf</code> attribute. The following example annotates the 261<code>setWallpaper</code> method to ensure that the caller of the method has the 262<code>permission.SET_WALLPAPERS</code> permission. </p> 263 264<pre> 265@RequiresPermission(Manifest.permission.SET_WALLPAPER) 266public abstract void setWallpaper(Bitmap bitmap) throws IOException; 267</pre> 268 269<p>This example requires the caller of the 270<code>updateVisitedHistory</code> method to have both read and write bookmark history permissions. </p> 271 272<pre> 273@RequiresPermission(allOf = { 274 Manifest.permission.READ_HISTORY_BOOKMARKS, 275 Manifest.permission.WRITE_HISTORY_BOOKMARKS}) 276public static final void updateVisitedHistory(ContentResolver cr, String url, boolean real) { 277 ... 278} 279</pre> 280 281 282<h2 id="check-result">Adding CheckResults Annotations</h2> 283<p>Use the <code>@CheckResults</code> annotation to 284validate that a method's result or return value is actually used. The following example annotates 285the <code>checkPermissions</code> method to ensure the return value of the method is actually 286referenced. It also names the 287<a href="{@docRoot}reference/android/content/ContextWrapper.html#enforcePermission">enforcePermission</a> 288method as a method to be suggested to the developer as a replacement. </p> 289 290 291 292<pre> 293@CheckResult(suggest="#enforcePermission(String,int,int,String)") 294public abstract int checkPermission(@NonNull String permission, int pid, int uid); 295</pre> 296 297{@link android.support.annotation.StringDef @StringDef} 298 299 300<h2 id="call-super">Adding CallSuper Annotations</h2> 301<p>Use the <code>@CallSuper</code> annotation to validate that an 302overriding method calls the super implementation of the method. The following example annotates 303the <code>onCreate</code> method to ensure that any overriding method implementations call 304<code>super.onCreate()</code>. </p> 305 306<pre> 307@CallSuper 308protected void onCreate(Bundle savedInstanceState) { 309} 310</pre> 311 312 313 314<h2 id="enum-annotations">Creating Enumerated Annotations</h2> 315<p>Use the {@link android.support.annotation.IntDef @IntDef} and 316{@link android.support.annotation.StringDef @StringDef} annotations 317so you can create enumerated annotations of integer and string sets to validate other types of code 318references, such as passing references to a set of constants. </p> 319 320<p>The following example illustrates the steps to create an enumerated annotation that ensures 321a value passed as a method parameter references one of the defined constants.</p> 322 323<pre> 324import android.support.annotation.IntDef; 325... 326public abstract class ActionBar { 327 ... 328 //Define the list of accepted constants 329 @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS}) 330 331 //Tell the compiler not to store annotation data in the <code>.class</code> file 332 @Retention(RetentionPolicy.SOURCE) 333 334 //Declare the <code>NavigationMode</code> annotation 335 public @interface NavigationMode {} 336 337 //Declare the constants 338 public static final int NAVIGATION_MODE_STANDARD = 0; 339 public static final int NAVIGATION_MODE_LIST = 1; 340 public static final int NAVIGATION_MODE_TABS = 2; 341 342 //Decorate the target methods with the annotation 343 @NavigationMode 344 public abstract int getNavigationMode(); 345 346 //Attach the annotation 347 public abstract void setNavigationMode(@NavigationMode int mode); 348 349</pre> 350 351<p>When you build this code, a warning is generated if the <code>mode</code> parameter does 352not reference one of the defined constants (<code>NAVIGATION_MODE_STANDARD</code>, 353<code>NAVIGATION_MODE_LIST</code>, or <code>NAVIGATION_MODE_TABS</code>).</p> 354 355<p>You can also define an annotation with a <code>flag</code> to check if a parameter 356or return value references a valid pattern. This example creates the 357<code>DisplayOptions</code> annotation with a list of valid <code>DISPLAY_</code> constants. </p> 358 359<pre> 360import android.support.annotation.IntDef; 361... 362 363@IntDef(flag=true, value={ 364 DISPLAY_USE_LOGO, 365 DISPLAY_SHOW_HOME, 366 DISPLAY_HOME_AS_UP, 367 DISPLAY_SHOW_TITLE, 368 DISPLAY_SHOW_CUSTOM 369}) 370@Retention(RetentionPolicy.SOURCE) 371public @interface DisplayOptions {} 372 373... 374</pre> 375 376<p>When you build code with an annotation flag, a warning is generated if the decorated parameter 377or return value does not reference a valid pattern.</p> 378 379 380