Search code examples
javaandroidannotations

Why do libraries use annotations?


I always wondered why android support libraries use annotations?

I have implemented some of the common android libraries like ButterKnife, Retrofit. However, I see one common behavior in these. They use annotations to provide their functionalities. I wondered why didn't they used some method or interfaces to implement the functionality they provide, is there any advantage in using annotation over these?


Solution

  • I always wondered why android support libraries use annotations?

    I have implemented some of the common android libraries like ButterKnife, Retrofit. However I see one common behavior in these. They use annotations to provide their functionalities.

    There are different purposes for default annotations and specific annotations that used by ButterKnife or Retrofit. Default annotations like @Override, @NonNull, @StringRes, @IntRes, etc is a way to tell the compiler about specific constraint for the code.

    Specific annotations like @BindView or @OnClick in ButterKnife are used for code generation. ButterKnife Annotation processor will be looking for all the matching annotations and generating the code according to the annotation as the rule.

    I wondered why didn't they used some method or interfaces to implement the functionality they provide, is there any profit in using annotation over these?

    They can provide the functionally like you have said but it's usually achieved by using a reflection which comes at a high cost in terms of performance and hard to maintain, more details at https://softwareengineering.stackexchange.com/questions/101187/are-there-problems-with-using-reflection for details. Hence code generation is used.