android:构建一个可以穿入任何参数的ViewModelProvider.Factory

构建一个可以传入任何参数的ViewModelProvider.Factory

现状分析

ViewModel大家都知道,默认情况下有两个工厂,NewInstanceFactory 和 AndroidViewModelFactory。

  1. 如果需要构造无参的ViewModel直接使用NewInstanceFactory即可。
  2. 如果需要构造带有Application的参数则使用AndroidViewModelFactory即可。

但是如果需要传入更多的参数呢?

一般我们会自定义Factory,来实现。
比如:

class MyViewModelFactory(private val dao: SimpleStudentDao) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(SimpleViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return SimpleViewModel(dao) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class.")
    }

}

自定义Factory,然后传入需要的参数,但是这样每次都创建一个Factory是不是太不方便了呢?能不能出现一个万能的Factory,直接匹配需要的参数呢?

如何处理

答案是反射。

  • 将需要的参数放到数组里面传递给Factory
  • 通过反射获取到对应ViewModel类的构造函数集合
  • 匹配参数数量
  • 匹配参数类型
    核心代码如下:
private static <T> Constructor<T> find(Class<T> modelClass, Object[] signature) {
        Constructor<T> hitConstructor = null;
        final Constructor<?>[] constructors = modelClass.getConstructors();
        for (Constructor<?> constructor :constructors) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();

            int parameterCount = parameterTypes.length;
            if (parameterCount != signature.length) {
                continue;
            }
            boolean match = match(signature, parameterTypes, parameterCount);
            if (match) {
                hitConstructor = (Constructor<T>) constructor;
                break;
            }
        }
        return hitConstructor;
    }

    private static boolean match(Object[] signature, Class<?>[] parameterTypes, int parameterCount) {
        boolean match = true;
        for (int i = 0; i < parameterCount; i++) {
            Class<?> clz = parameterTypes[i];
            Class<?> targetClz = signature[i] == null ? null : signature[i].getClass();
            boolean equals;
            if (clz == null) {
                equals = targetClz == null;
            } else {
                if (targetClz == null) {
                    equals = !clz.isPrimitive();
                } else {
                    equals = clz.isAssignableFrom(targetClz);
                }
            }
            if (!equals) {
                match = false;
                break;
            }
        }
        return match;
    }

完整代码如下所示:

public class SupportViewModelFactory implements ViewModelProvider.Factory {
    private final Object[] param;

    public SupportViewModelFactory(Object[] param) {
        this.param = param;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        int count = param == null ? 0 : param.length;
        try {
            if (count <= 0) {
                return modelClass.newInstance();
            }
            return find(modelClass, param).newInstance(param);
        } catch (IllegalAccessException | NullPointerException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
            String msg = "";
            if (param != null) {
                msg = "param:" + Arrays.toString(param);
            }
            throw new RuntimeException(msg, e);
        }
    }

    private static <T> Constructor<T> find(Class<T> modelClass, Object[] signature) {
        Constructor<T> hitConstructor = null;
        final Constructor<?>[] constructors = modelClass.getConstructors();
        for (Constructor<?> constructor :constructors) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();

            int parameterCount = parameterTypes.length;
            if (parameterCount != signature.length) {
                continue;
            }
            boolean match = match(signature, parameterTypes, parameterCount);
            if (match) {
                hitConstructor = (Constructor<T>) constructor;
                break;
            }
        }
        return hitConstructor;
    }

    private static boolean match(Object[] signature, Class<?>[] parameterTypes, int parameterCount) {
        boolean match = true;
        for (int i = 0; i < parameterCount; i++) {
            Class<?> clz = parameterTypes[i];
            Class<?> targetClz = signature[i] == null ? null : signature[i].getClass();
            boolean equals;
            if (clz == null) {
                equals = targetClz == null;
            } else {
                if (targetClz == null) {
                    equals = !clz.isPrimitive();
                } else {
                    equals = clz.isAssignableFrom(targetClz);
                }
            }
            if (!equals) {
                match = false;
                break;
            }
        }
        return match;
    }

    public static boolean equals(Object[] a, Object[] a1) {
        if (a == a1)
            return true;
        if (a == null || a1 == null)
            return false;

        int length = a.length;
        if (a1.length != length)
            return false;

        for (int i = 0; i < length; i++) {
            Object o1 = a[i];
            Object o2 = a1[i];
            if (!(Objects.equals(o1, o2))) {
                return false;
            }
        }

        return true;
    }
}

‍♀️。欢迎技术探讨噢!

你可能感兴趣的:(android,my,Jetpack,android,java,开发语言)