依赖注入——Annotation
发布时间:2020-12-13 22:29:14 所属栏目:百科 来源:网络整理
导读:在Android开发中,为了避免重复的代码,如: Button btn; btn = ( Button )findViewById(R.id.btn); 在代码中可以使用如下的方式: @ InjectView(R.id.user) EditText username ; 这里使用的是Butter Knife库 但是在使用上面类似的库时,可能会感到不放心,
在Android开发中,为了避免重复的代码,如: Button btn;
btn = (Button)findViewById(R.id.btn);
在代码中可以使用如下的方式: @InjectView(R.id.user) EditText username;
这里使用的是Butter Knife库 但是在使用上面类似的库时,可能会感到不放心,想了解它们大概的实现原理,这时就需要复习一下Java的Annotation的相关知识。 之后模拟了依赖注入的过程,其中涉及到Annotation的定义和反射机制。 总之,使用定义的Annotion进行注解,然后通过反射对注解进行处理。 注解示例: @CustomInject(id = R.id.btn)
private Button btn;
@CustomInject(id = R.id.text)
private TextView text;
处理示例: public class InjectTool {
public static void process(Activity activity){
try{
Class clazz = activity.getClass();
for(Field field : clazz.getDeclaredFields()){
// Setting this to true prevents IllegalAccessExceptions.
field.setAccessible(true);
// Returns,for this element,the annotation with the specified type,or null if no annotation with the specified type is present
CustomInject customInject = field.getAnnotation(CustomInject.class);
if(customInject!=null){
// 获取@CustomInject(id = R.id.btn)中id的值
int id = customInject.id();
if (id>0){
// 赋值
field.set(activity,activity.findViewById(id));
}
}
}
}catch (Exception exception){
exception.printStackTrace();
}
}
}
下面是完整的代码地址 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |