反射让一个类及其超类的的字段全部为null--设置字段为null

来源:互联网 发布:广东淘宝商城 编辑:程序博客网 时间:2024/06/10 10:42
package com.ipace.chaoJie.utils;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** * 该方法 *不能设置父类的字段为null * */public class MakeColumnNull0False<T> {    public  T f(T o)  {        /**         ******下面一直到while*会得到该类及其父类的所有字段*********************************************************************************         * */        List<Field> fieldList=new ArrayList<>();        Class<?> aClass = o.getClass();        while (aClass != null) {//while得到所有超类的字段属性            fieldList.addAll(Arrays.asList(aClass.getDeclaredFields()));            aClass = aClass.getSuperclass(); //得到父类,然后赋给自己        }        /**         *****上面会得到该类及其父类的所有字段***********************************************************************************         * */        for(Field field:fieldList){            field.setAccessible(true);            Class<?> type = field.getType();            if("int".equals(type.getName())){                try {                    field.setInt(o,0);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }else if("double".equals(type.getName())){                try {                    field.setDouble(o,0d);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }            else if("float".equals(type.getName())){                try {                    field.setFloat(o,0f);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }else if("long".equals(type.getName())){                try {                    field.setLong(o,0L);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }else if("short".equals(type.getName())){                try {                    field.setShort(o, (short) 0);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }else if("boolean".equals(type.getName())){                try {                    field.setBoolean(o,false);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }else{                try {                    field.set(o,null);                } catch (IllegalAccessException e) {                    System.out.println("该类的该字段类型为"+type.getName()+"无法转换为null或者0");                }            }        }        return o;    }    }
阅读全文
0 0
原创粉丝点击