我正在尝试制作一些自定义注释来减少 Android 应用程序中的样板代码。我知道这是可行的,因为有许多库使用相同的技术,例如黄油刀
。想象一下这个简单的 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));
}
}
}
关于java - 自定义注解Java/android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34733443/