Live Templates for Annotators
An annotation is a form of syntactic metadata which can be added into Java source code. Using it, you can add some additional information for parameters, methods and classes. Personally, I use @NonNull
and @Nullable
annotations a lot. With them, I know a parameter requirement and a mismatched type easily.
public Image(@NonNull String url, @NonNull String title);
/**
* A title in the Image constructor is @NonNull but
* a title parameter here is @Nullable. There is a mismatched type
*/
public static Image createImage(@NonNull String url, @Nullable String title) {
return new Image(url, title);
}
public Image(@NonNull String url, @NonNull String title) {
}
There are really good annotations. However, I’ve noticed that two things.
- Typing
@NonNull
and@Nullable
is not that short. - After typing it, I often need to import the package.
I need to find a better way. Fortunately, Live Templates saves me. You can see how I do it now. I just type nu<space>
and nn<space>
. This is not only about replacing the text but also about importing the package.
To do it, open Preference > Live Templates. Then,
- Click ‘+’ to add a new one
- Type
nn
in Abbreviation - Type
@android.support.annotation.NonNull
(There is a space at the end) in Template text - Select ‘Space’ in Expand with
- Check ‘Use static import if possible’
- Define applicable contexts as ‘java > expression’ and ‘java > declaration’
This is a setting for @Nullable
.
If you want to know more advanced live templates, you can see my live template for the argument captor.
![]()
$1$
and$2$
are variables. For this, I don’t check ‘Use static import if possible’