适合初学者的反射代码

 

 

以上为一个同事写的关于脱敏的一段代码 ,这个关于脱敏的需求我感受是一段很是完美的关于“反射”的需求的应用场景,适合初学者学习前端

需求内容:

很简单 ,安所有门要求,针对客户的基础信息数据例如手机号、身份证、姓名等信息进行脱敏,防止客户信息外泄,其中主要包括两个部分java

接口和日志。spring

分析:

针对接口部分,我公司进行先后端分离的操做,前端和后端的交互大部分以json交互为主,springmvc能够讲java对象转成成apache

json格式,大部分传给前端的都是json对象,因而乎,个人同事就将脱敏接口的动做概括为脱敏对象的动做, 可是先后端接口json

有几百个,涉及的类更是不只期数,不可能针对没一个返回接口的对象都作一些从新定义值的处理 ,因而反射应运而生后端

 

实现方法:

该同事 写了一个脱敏的工具类(SensitiveFormatter),包含两种方法安全

    public static void formatObjectByAttributes(Object o, int type, String... attributes) {
    private static void setValue(Field f, Object o, int type) {
 mvc

针对须要脱敏的对象和字段出直接调用该脱敏类 app

appDao为脱敏的对象,SensitiveFormatter.NAME为脱敏的类型 ,Name,为脱敏的变量名称前后端分离

 SensitiveFormatter.formatObjectByAttributes(appDao, SensitiveFormatter.NAME, "Name");

formatObjectByAttributes 方法,对该对象进行反射,或者到与Name对应的Field 

{java.lang.reflect.Field 为咱们提供了获取当前对象的成员变量的类型,和从新设值的方法},

Field field = o.getClass().getDeclaredField(attribute);

·而后在这个File重新进行设置,调用的正式setValue方法
                 

  String name = (String) f.get(o);
                     if (StringUtils.isNotBlank(name) && name.length() > 1) {
                        name = name.charAt(0) + name.substring(1).replaceAll("[^x00-xff]|\\w", "*");
                        f.set(o, name);
                    }

 

代码和原理很简单 ,一下是所有代码,能够做为学习的参考

 

package com.paic.common.utils;


import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;


public class SensitiveFormatter {

    private static Log logger = LogFactory.getLog(SensitiveFormatter.class);

    public static final int NAME = 1;

    public static final int PHONE = 2;

    public static final int ID_NO = 3;

    public static final int SEX = 4;

    /**
     * 参数脱敏处理List数据
     * 反射处理POJO
     *
     * @param list       脱敏List对象
     * @param type       脱敏类型
     * @param attributes 脱敏成员变量名称
     * @throws Exception
     */
    public static void formatListByAttributes(List list, int type, String... attributes) {
        if (attributes == null || attributes.length <= 0) {
            return;
        }

        if (list != null && list.size() > 0) {
            for (String attribute : attributes) {
                try {
                    Field field = list.get(0).getClass().getDeclaredField(attribute);
                    for (Object o : list) {
                        setValue(field, o, type);
                    }
                } catch (Exception e) {
                    logger.error("SensitiveFormatter --- NoSuchFieldException : " + e.getMessage());
                }
            }

        }
    }

    /**
     * 参数脱敏处理Object数据
     * 反射处理POJO
     *
     * @param o          脱敏对象
     * @param type       脱敏类型
     * @param attributes 脱敏成员变量名称
     * @throws Exception
     */
    public static void formatObjectByAttributes(Object o, int type, String... attributes) {
        if (attributes == null || attributes.length <= 0) {
            return;
        }

        if (o != null) {
            for (String attribute : attributes) {
                try {
                    Field field = o.getClass().getDeclaredField(attribute);
                    setValue(field, o, type);
                } catch (Exception e) {
                    logger.error("SensitiveFormatter --- NoSuchFieldException : " + e.getMessage());
                }

            }
        }
    }


    /**
     * 参数脱敏处理List<Map>数据
     *
     * @param list       脱敏List<Map>对象
     * @param type       脱敏类型
     * @param attributes 脱敏成员变量名称
     * @throws Exception
     */
    public static void formatListWithMapByAttributes(List<Map<String, Object>> list, int type, String... attributes) {
        if (attributes == null || attributes.length <= 0) {
            return;
        }
        if (list != null && list.size() > 0) {
            for (String attribute : attributes) {
                try {
                    for (Map map : list) {
                        setMapValue(map, attribute, type);
                    }
                } catch (Exception e) {
                    logger.error("SensitiveFormatter --- NoSuchFieldException : " + e.getMessage());
                }
            }

        }
    }

    /**
     * 参数脱敏处理Map数据
     *
     * @param map        脱敏Map对象
     * @param type       脱敏类型
     * @param attributes 脱敏成员变量名称
     * @throws Exception
     */
    public static void formatListWithMapByAttributes(Map<String, Object> map, int type, String... attributes) {
        if (attributes == null || attributes.length <= 0) {
            return;
        }
        if (map != null) {
            for (String attribute : attributes) {
                try {
                    setMapValue(map, attribute, type);
                } catch (Exception e) {
                    logger.error("SensitiveFormatter --- NoSuchFieldException : " + e.getMessage());
                }
            }

        }
    }

    /**
     * 注解脱敏处理list数据
     *
     * @param list 脱敏List对象
     * @throws Exception
     */
    public static void formatListByAnnotation(List list) {
        if (list != null && list.size() > 0) {
            for (Field field : list.get(0).getClass().getDeclaredFields()) {
                //得到注解的对象
                SensitiveFormat sensitiveFormat = field.getAnnotation(SensitiveFormat.class);
                if (sensitiveFormat != null) {
                    for (Object o : list) {
                        setValue(field, o, sensitiveFormat.type());
                    }
                }
            }
        }
    }

    /**
     * 注解脱敏处理object数据
     *
     * @param o 脱敏对象
     * @throws Exception
     */
    public static void formatObjectByAnnotation(Object o) {
        if (o != null) {
            for (Field field : o.getClass().getDeclaredFields()) {
                //得到注解的对象
                SensitiveFormat sensitiveFormat = field.getAnnotation(SensitiveFormat.class);
                if (sensitiveFormat != null) {
                    setValue(field, o, sensitiveFormat.type());
                }
            }
        }
        new SimplePropertyPreFilter();
    }

    private static void setValue(Field f, Object o, int type) {
    	System.out.println(o);
        f.setAccessible(true);
        try {
            switch (type) {
                case NAME:
                    String name = (String) f.get(o);
                    if (StringUtils.isNotBlank(name) && name.length() > 1) {
                        name = name.charAt(0) + name.substring(1).replaceAll("[^x00-xff]|\\w", "*");
                        f.set(o, name);
                    }
                    break;
                case PHONE:
                    f.set(o, CommonUtil.addCode((String) f.get(o), 3, 2));
                    break;
                case ID_NO:
                    f.set(o, CommonUtil.addCode((String) f.get(o), 1, 1));
                    break;
                case SEX:
                    if (f.getType().equals(String.class)) {
                        f.set(o, "*");
                    } else {
                        f.set(o, null);
                    }
                default:
                    break;
            }
        } catch (Exception e) {
            logger.error("SensitiveFormatter --- setValue --- occurs error : " + e.getMessage());
        }

    }

    private static void setMapValue(Map<String, Object> map, String attributeName, int type) {
        try {
            switch (type) {
                case NAME:
                    String name = (String) map.get(attributeName);
                    if (StringUtils.isNotBlank(name) && name.length() > 1) {
                        name = name.charAt(0) + name.substring(1).replaceAll("[^x00-xff]|\\w", "*");
                        map.put(attributeName, name);
                    }
                    break;
                case PHONE:
                    map.put(attributeName, CommonUtil.addCode((String) map.get(attributeName), 3, 2));
                    break;
                case ID_NO:
                    map.put(attributeName, CommonUtil.addCode((String) map.get(attributeName), 1, 1));
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            logger.error("SensitiveFormatter --- setMapValue --- occurs error : " + e.getMessage());
        }

    }
    
    public static void main(String[] args) {
    	A a =new A();
    	a.setName("ss");
    	formatObjectByAttributes(a,1,"name");
    	System.out.println(a.getName());
	}
}

class A{
	 String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	 
}
相关文章
相关标签/搜索