反射 - 继承的字段全部为null或为空

时间:2016-11-15 10:24:08

标签: java reflection

我有一个类(带有超类)我要检查所有字段是否为NULL,或者它是否为Collection,它是空的。使用以下代码,我可以检查NULL以及它是否为Collection,但我似乎无法强制使用Collection来检查它的大小:

enable-time-statistics=true
statistic-sampling-enabled=true
...

但是这会导致java.lang.ClassCastException:无法将java.lang.reflect.Field强制转换为java.util.Collection

如何获取列表的大小?

2 个答案:

答案 0 :(得分:4)

您无法将字段转换为集合。您可以将字段对象强制转换为集合。试试这个:

System.err.println(Collection.class.cast(field.get(object)).size());

答案 1 :(得分:0)

下面的代码将使用java反射将空白空字符串转换为null:

package reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Sachin Rane on 7/1/21
 */
public class ReflectionUtils {
    public static void main(String[] args) {
        Employee employee = new Employee();
        employee.setName("Sachin");
        employee.setCity("");//this will set to null

        replaceAllEmptyStringFieldsWithNull(employee);
        
        if (null == employee.getCity()) {
            System.out.println("replaceAllEmptyStringFieldsWithNull converted blank string to null");
        }
    }

    public static void replaceAllEmptyStringFieldsWithNull(Object object) {
        if (null == object) {
            return;
        }
        Method[] methodsOfObject = object.getClass().getDeclaredMethods();
        Method methodRef = null;
        try {
            for (Method method : methodsOfObject) {
                methodRef = method;
                method.setAccessible(true);
                if (isGetType(method)) {
                    //skip list, set, map or array objects
                    if (skipObjectsCheck(method)) {
                        continue;
                    }
                    if (method.getReturnType() == String.class) {
                        String value = (String) method.invoke(object);
                        if ("".equals(value)) {
                            Field field = getFieldByFieldName(object, method.getName().replace("get", ""));
                            if (null != field) {
                                field.setAccessible(true);
                                field.set(object, null);
                            }
                        }
                    } else {
                        replaceAllEmptyStringFieldsWithNull(method.invoke(object));
                    }
                }
            }
        } catch (IllegalAccessException ex) {
            System.out.println("IllegalAccessException while invoking method for class : " + object.getClass().getName()
                    + " and method : " + (null != methodRef ? methodRef.getName() : null));
        } catch (InvocationTargetException ex) {
            System.out.println("InvocationTargetException while invoking method for class : " + object.getClass().getName()
                    + " and method : " + (null != methodRef ? methodRef.getName() : null));
        }

    }

    static boolean skipObjectsCheck(Method method) {
        if (method.getReturnType().isArray()) return true;
        if (!(method.getGenericReturnType() instanceof ParameterizedType)) return false;
        ParameterizedType parametrizedReturnType = (ParameterizedType) method.getGenericReturnType();
        if (parametrizedReturnType.getRawType() == List.class
                || parametrizedReturnType.getRawType() == Set.class
                || parametrizedReturnType.getRawType() == Map.class) {
            return true;
        }
        return false;
    }

    static Field getFieldByFieldName(Object obj, String fieldName) {
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field f : fields){
            if (f.getName().equalsIgnoreCase(fieldName)) {
                return f;
            }
        }
        return null;
    }

    static boolean isGetType(Method method) {
        if (method.getName().startsWith("get")) return true;
        return false;
    }

    private static class Employee {
        String name;
        String city;
        List<String> list;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public List<String> getList() {
            return list;
        }

        public void setList(List<String> list) {
            this.list = list;
        }
    }
}

输出

replaceAllEmptyStringFieldsWithNull converted blank string to null
相关问题