简体   繁体   中英

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

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));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM