自定义注释Java / android

时间:2016-01-12 00:09:59

标签: java android reflection annotations

我正在尝试制作一些自定义注释来减少我的Android应用中的锅炉板代码。我知道它是可行的,因为有许多库使用相同的技术,例如ButterKnife。想象一下这个简单的Android Activity。我想知道如何让CustomLibrary.printGoodInts以我想要的方式工作(也许使用反射)。

PS:如果我要问的是疯狂而且太多而不是一个简单的答案,那么一个好的参考对我来说也会很棒:)

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 个答案:

答案 0 :(得分:1)

您必须创建@GoodInt @interface。这是一个例子:

import java.lang.annotation.*;

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

}

要打印具有此注释的所有字段,您可以执行以下操作:

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