编辑
使用反射初始化对象
本文访问次数:0

服务器端的开发人员告诉Android开发人员,他们做不到只返回有用的数据,并且空数据统统返回null,Android端的开发人员只好使用Java反射机制进行初始化,这样整个项目才不会被if-else语句刷屏,完整代码如下

public static void instantiateFieldsOfObject(Object object, Set<String> packages) throws IllegalArgumentException, InstantiationException, IllegalAccessException {
        Field[] fields = object.getClass().getDeclaredFields();

        for (Field field : fields) {
            String fieldName = field.getName();
            Class<?> fieldClass = field.getType();

            if (fieldClass.isPrimitive()) {
                continue;
            }

            boolean inPackage = false;
            boolean isList = false;
            boolean isMap = false;
            boolean isString = false;
            for (String pack : packages) {
                if (fieldClass.equals(List.class)) {
                    isList = true;
                } else if (fieldClass.equals(Map.class)) {
                    isMap = true;
                } else if (fieldClass.equals(String.class)) {
                    isString = true;
                } else if (fieldClass.getPackage().getName().startWith(pack)) {
                    inPackage = true;
                }
            }
            if (!inPackage && !isList && !isMap && !isString) {
                continue;
            }

            boolean isAccessible = field.isAccessible();
            field.setAccessible(true);

            Object fieldValue = field.get(object);
            if (fieldValue == null) {
                if (isList) {
                    field.set(object, new ArrayList());
                } else if (isMap) {
                    field.set(object, new HashMap());
                } else if (isString) {
                    field.set(object, "");
                } else {
                    field.set(object, fieldClass.newInstance());
                }
            }

            field.setAccessible(isAccessible);

            if (inPackage) {
                fieldValue = field.get(object);
                instantiateFieldsOfObject(fieldValue, packages);
            }
        }
    }

使用方法如下

ResponseModel object = com.alibaba.fastjson.JSON.parseObject(response, ResponseModel.class);
Set<String> packages = new HashSet<>();
packages.add("com.example.android");
try {
    instantiateFieldsOfObject(object, packages);
} catch (IllegalAccessException e) {
    ...
} catch (InstantiationException e) {
    ...
} catch (IllegalArgumentException e) {
    ...
}

这个解决方法来自于stack overflow社区。

没有任何评论