java class 属性 null 给个默认值

//本方法只是参考

public static void setFieldNotNull(Object obj) throws Exception {
    getField(obj.getClass(), obj);
}

private static void getField(Class clazz, Object obj) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
    if (clazz == null) return;
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field field : declaredFields) {
        field.setAccessible(true);
        if (field.get(obj) == null) {
            if (field.getType().toString().equals("class java.lang.String")) {
                field.set(obj, "");
            } else if (field.getType().toString().equals("class java.lang.Integer")) {
                field.set(obj, 0);
            } else if (field.getType().toString().equals("class java.math.BigDecimal")) {
                field.set(obj, new BigDecimal("0.0"));
            } else if (field.getType().toString().equals("class java.lang.Long")) {
                field.set(obj, 0L);
            } else {
                Constructor constructor = field.getType().getConstructor();
                Object curObj = constructor.newInstance();
                field.set(obj, curObj);
                getFields(field.getType(), curObj);
            }
        } else {
            if ((field.getType().toString().equals("class java.lang.String")
                    || field.getType().toString().equals("class java.lang.Integer")
                    || field.getType().toString().equals("class java.math.BigDecimal")
                    || field.getType().toString().equals("class java.lang.Long"))) {

            } else {
                getField(field.getType(), field.get(obj));
            }
        }
    }
    clazz = clazz.getSuperclass();
    getField(clazz, obj);
}

你可能感兴趣的:(JAVA,webview,java,蓝桥杯)