Kasra
Kasra

Reputation: 3155

Custom annotation Java / android

I'm trying to make some custom annotations to reduce boiler plate code in my android apps. I know it is doable since there are many libraries using the same technique, e.g. ButterKnife. So Imagine this simple Android Activity. I'd like to know how to make CustomLibrary.printGoodInts work the way I want (perhaps using reflection).

PS: if what I am asking is crazy and too much to be a simple answer, a good reference will do great for me too :)

public class MainActivity extends Activity {

    @GoodInt
    private int m1 = 10;

    @GoodInt
    private int m2 = 20;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      CustomLibrary.printGoodInts(this); // <<<<<<<<<< This is where magic happens
   }
}


public class CustomLibrary {
    public static void printGoodInts(Object obj){
        // Find all member variables that are int and labeled as @GoodInt
        // Print them!!
    }
}

Upvotes: 2

Views: 350

Answers (1)

Titus
Titus

Reputation: 22484

You will have to create a @GoodInt @interface. Here is an example:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) // allow this annotation to be set only for fields
public @interface GoodInt {

}

And to print all the fields which have this annotation, you can do this:

public static void printGoodInts(Object obj) throws IllegalArgumentException, IllegalAccessException {
    Field[] fields = obj.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(GoodInt.class)) {
            field.setAccessible(true);
            System.out.println(field.getName() + " = " + field.get(obj));
        }
    }
}

Upvotes: 2

Related Questions