[英]Custom annotation Java / android
我正在尝试进行一些自定义注释,以减少我的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!!
}
}
您将必须创建一个@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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.