【问题标题】:Custom annotation Java / android自定义注解 Java/android
【发布时间】:2016-01-12 00:09:58
【问题描述】:

我正在尝试制作一些自定义注释以减少我的 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!!
    }
}

【问题讨论】:

    标签: java android reflection annotations


    【解决方案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));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-13
      • 2011-06-12
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2022-01-24
      • 2013-09-28
      相关资源
      最近更新 更多