美文网首页
Activity基于注解传递数据

Activity基于注解传递数据

作者: 咚咚_Coding | 来源:发表于2021-06-25 19:33 被阅读0次

AutoIntentUtils

public class AutoIntentUtils {
public static void inject(Activity activity) {
    Class<? extends Activity> aClass = activity.getClass();
    Field[] fields = aClass.getDeclaredFields();
    for (Field field : fields){
        if (field.isAnnotationPresent(Autowired.class)){
            Autowired autowired = field.getAnnotation(Autowired.class);
            String element = autowired.value();
            Intent intent = activity.getIntent();
            if (intent == null){
                return;
            }
            if (TextUtils.isEmpty(element)){
                element = field.getName();
            }
            Bundle bundle = intent.getExtras();
            Object value = bundle.get(element);
            setFieldValue(activity, field, value);
        }
    }
      }

 private static void setFieldValue(Activity activity, Field field, Object stringExtra) {
    field.setAccessible(true);
    try {
        field.set(activity, stringExtra);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
}

自定义注解

 @Target(ElementType.FIELD)
 @Retention(RetentionPolicy.RUNTIME)
 public @interface Autowired {
  String value() default "";
 }

相关文章

网友评论

      本文标题:Activity基于注解传递数据

      本文链接:https://www.haomeiwen.com/subject/fvcoyltx.html