Annotations
Most Java developers are familiar with annotations. These are the @
-prefixed values that decorate classes, methods, fields, and so on:
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
Context appContext=InstrumentationRegistry.getTargetContext();
assertEquals("com.commonsware.jetpack.hello", appContext.getPackageName());
}
}
Here, @RunWith
and @Test
are annotations. These happen to be from JUnit (specifically JUnit 4) and are used to teach a JUnit test runner:
- How to run a particular test class (“this test class needs to be run with the assistance of
AndroidJUnit4
”) - Which methods represent test methods that should be executed when running the test
Kotlin’s annotations are very similar to Java’s, with a few syntax differences.
Where Annotations Come From
The Java example above shows a pair of annotations from JUnit 4. JUnit 4 is annotation-based; it supplies quite a few annotations.
Overall, there are a few different places where annotations can come from.
Kotlin
Kotlin has some annotations that are part of the Kotlin standard library. One that we will examine in this chapter is Kotlin’s take on the @Deprecated
annotation, used to denote some code (class, method, field, etc.) that should no longer be used.
Java
If you are using Kotlin/JVM (e.g., for Android development), Java’s annotations are also available to you. You are unlikely to use many of them directly yourself — for example, Java’s @Override
annotation is replaced by Kotlin’s override
keyword. However, technically, they are available to you.
Libraries
Most annotations come from libraries. These libraries will come with “annotation processors” that know how to scan a code base for annotations and do something useful with them, either:
- At compile time for code generation, or
- At runtime to assist with code execution
JUnit 4 falls in the latter category, using annotations to help guide how to execute your tests. Dagger — a popular dependency injection framework for Java — uses them at compile time for code generation.
You!
You are welcome to create your own annotations.
Most developers will have little need to do this. Some will create annotations designed to be used by other annotation processors, such as using custom annotations with Dagger to help guide its dependency injection rules. And a few enterprising developers will create their own annotation processors. This book will not get into how to implement an annotation processor, though we will see some simple custom annotations.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.