2

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!!
    }
}

1 Answer 1

2

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));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.