反射与注解实现页面跳转参数注入

概述

本文主要分享基于反射与注解实现页面跳转参数注入。

实现思路:

  • 自定义AutoWired注解标记需要注入的成员属性
  • 查找页面中带AutoWired注解的属性
  • 根据AutoWired注解获取传递参数的key,通过Bundle获取对应的Value并使用反射对属性赋值

自定义AutoWired注解

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

查找页面中带AutoWired注解的属性,获取传递参数的key,通过Bundle获取对应的Value并使用反射对属性赋值

关键代码如下:

 public static void inject(Activity activity) {
    try {
        //注意:反射是基于Class
        Class<? extends Activity> aClass = activity.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();

        Bundle extras = activity.getIntent().getExtras();

        for (Field field : declaredFields) {
            if (field.isAnnotationPresent(AutoWired.class)) {
                AutoWired autoWired = field.getAnnotation(AutoWired.class);
                String key = TextUtils.isEmpty(autoWired.value()) ? field.getName() : autoWired.value();

                //判断Bundle中是否传递了对应key的数据
                if (extras.containsKey(key)) {
                    //获取key对应的value
                    Object value = extras.get(key);

                    //注意:Parcelable数组类型不能直接设置,其他的都可以.
                    //获得数组单个元素类型
                    Class<?> componentType = field.getType().getComponentType();

                    // class1.isAssignableFrom(class2) 判定此 class1 对象所表示的类或接口与指定的 class2 参数所表示的类或接口是否相同,或是否是其超类或超接口
                    if (field.getType().isArray() && Parcelable.class.isAssignableFrom(componentType)) {
                        Object[] objects = (Object[]) value;
                        //创建对应类型的数组并由objects拷贝,即拷贝成对应Parcelable类型的数组
                        Object[] realArr = Arrays.copyOf(objects, objects.length, (Class<? extends Object[]>) field.getType());
                        //重新对value赋值
                        value = realArr;
                    }
                    //设置访问权限
                    field.setAccessible(true);
                    //反射设置值
                    field.set(activity, value);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

页面传参数与页面注入参数

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void go2Second(View view) {
        ArrayList<Student> studentList = new ArrayList<>();
        studentList.add(new Student("fmt1"));
        studentList.add(new Student("fmt2"));

        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra("name", "fmt")
                .putExtra("sex", "男")
                .putExtra("myAge", 25)
                .putExtra("studentParcelable", new Student("fmt java"))
                .putExtra("personSerializable", new Person("fmt android"))
                .putExtra("studentParcelableArr", new Student[]{new Student("fmt1"), new Student("fmt2")})
                .putExtra("personSerializableArr", new Person[]{new Person("fmt1"), new Person("fmt2")})
                .putExtra("studentList", studentList);
        startActivity(intent);

    }
}

public class SecondActivity extends AppCompatActivity {

    @AutoWired
    String name;

    @AutoWired
    String sex;

    @AutoWired("myAge")
    int age;

    @AutoWired
    Student studentParcelable;

    @AutoWired
    Person personSerializable;

    @AutoWired
    Student[] studentParcelableArr;

    @AutoWired
    Person[] personSerializableArr;

    @AutoWired
    List<Student> studentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        ViewInjectUtils.inject(this);
        TextView textView = findViewById(R.id.textView);
        textView.setText(toString());
    }
}

完整代码实现

百度链接

密码:1hqx

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容