ATAT. The great power of Annotations, and what it can do for you!

Ahmed Ehab
AndroidPub
Published in
4 min readOct 12, 2018
Annotations are very powerful and helpful in android. image source (italiancoders)

In this blog we will talk about how to use annotations, to write less code and remove the parts of logic that repeat in different places to a single location.

This blog is a part of Android Tips And Tricks (ATAT) for Building a Robust Android App Series.

1- Why annotations:

Lots of people do not consider using annotation to refactor their code or make the entire architecture based around using the annotations, to add layers of validation or logic in a single place.

If we look closely we find that almost all of the libraries we use has some kind of annotations to generate code, validate state or inject objects, and with that making the whole process a lot easier to the people using their library.

That shows us that annotations are a very powerful tool we must use it to our advantage.

2. What annotations can make for you:

Now we will think of some cases you could annotations to help you, minimize your code and keep it consistent and goal oriented.

  1. Inject objects or views
  2. Make some validation before using a method
  3. Logging information for a specific method or class during execution
  4. Generate code using the metadata collected from the annotation

and so much more...

3. How to make your own annotations:

That's great and all, but how can I make my own annotations to try it out.

Well you will be using the java.lang.annotation package to make annotations

You then use the annotations you made and with some annotation processing and code generating you do any kind of logic like Injecting views as Butter Knife does.

A great article I recommend that talks about this is:

Custom Annotations in Android

Another way is to use AOP “Aspect-Oriented Programming” to add more power to your annotations, For those who haven’t heard about it, It’s an approach on programming that allows making modifications to the compiled code. AspectJ is an implementation of AOP used in Java. For this article, I will not go deeper into explaining AOP, but you can find plenty of documentation and examples on this subject.

To enable AspectJ on Android Studio, you could make your own gradle plugin that adds and configure aspectj to your project as we discussed in this series before ATAT. Gradle Tasks and Plugins, Something more Customized!

But for simplicity, there is a great Gradle plugin by Eduard Matsukov on GitHub. It is very easy to use

To add it to your project just add this to your projectbuild.gradle file.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

repositories {
google()
jcenter()
mavenCentral()

}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
classpath 'com.archinamon:android-gradle-aspectj:3.2.0'
}
}

then add this line to your appbuild.gradle or if you are making a new module then to this one.

apply plugin: 'com.archinamon.aspect

Now let us see an example on how to make a Simple annotation that will check the Internet connection and if there is a connection the method will work otherwise it will not be executed.

The first step we will make our annotation interface:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface RunWithInterne{

}

That’s the simple part. now let’s talk about two things.

@Target Specifies the elements on which this annotation can be used. In this case, we have ElementType.METHOD since we’re going to be annotating only methods. Other elements that can be annotated are:

@Retention annotation tells the compiler when will it be needed.

RetentionPolicy.RUNTIME The annotation should be available at runtime, for inspection via java reflection.

RetentionPolicy.CLASS The annotation would be in the .class file but it would not be available at runtime.

RetentionPolicy.SOURCE The annotation would be available in the source code of the program, it would neither be in the .class file nor be available at the runtime.

The second step is our Aspect.

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Aspect
public class ConnectionAspect {
private static final String RESTRICT_TO_INTERNET = "execution(@YOUR_PACKAGE_NAME.RunWithInterne * * (..))";


@Pointcut(value = RESTRICT_TO_INTERNET)
public void RestrictToInternetAnnotationMethod() {

}

@Around("RestrictToInternetAnnotationMethod()")
public void checkMethodConnection(ProceedingJoinPoint joinPoint) throws Throwable{

if(MyNetworkManager.isConnected()){ // A class i made to check for the Internet connection.
joinPoint.proceed();
}//if there is no Internet do nothing

}
}

With that the aspect is done, so let’s talk about what is done here:

First, we Add @Aspect at the start of the class to mark it as the Aspect.

Then we make a @Pointcut with the location of our annotation interface and add a wildcard (*) to make it work with any method name, return type and arguments.

Lastly, we add @Around on the method that will be called each time the annotation is used and inside it, we check for Internet connection (Or any other logic we want) if there is a connection we call proceed(), which will make the method continue execution otherwise the method will not be executed.

Our annotation in action will be like this:

@RunWithInterne
private void showToastInternetIsAvailable() {
Toast.makeText(this, "Internet is available", Toast.LENGTH_SHORT).show();
}

if we run the application this method will be executed only if there is Internet available.

This was a small example of what annotations can help you with, but i’m sure it’s power is visible and wide range of possible usages can be made with it.

The link to the example we just made can be found here.

Some resources that can discuss more in details:

Aspect-Oriented Programming in Android

Annotation Processing : Don’t Repeat Yourself, Generate Your Code

This is my first article here on medium so i hope it was clear, and if you found it helpful please add a clap for it, if there is any comments or ideas please say it in the comments, Enjoy your day.

--

--

Ahmed Ehab
AndroidPub

A mobile developer with love to all new technologies.