Android Annotation Processor Creating and Using Custom Annotations

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


For creating custom annotations we need to decide

  • Target - on which these annotations will work on like field level, method level, type level etc.
  • Retention - to what level annotation will be available.

For this, we have built in custom annotations. Check out these mostly used ones:


Target and what it means


Retention and what it means

Creating Custom Annotation

@Retention(RetentionPolicy.SOURCE) // will not be available in compiled class   
@Target(ElementType.METHOD) // can be applied to methods only
@interface CustomAnnotation{  
      int value();    

Using Custom Annotation

class Foo{  
  @CustomAnnotation(value = 1)  // will be used by an annotation processor
  public void foo(){..}  

the value provided inside @CustomAnnotation will be consumed by an Annotationprocessor may be to generate code at compile time etc.

Got any Android Question?