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