Java利用反射机制过滤集合内对象的属性字段

直接上代码:

package com.demo.test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.demo.po.EzsGoods;

public class FieldFilterUtil {
	/**
	* 字段过滤?
	* @author 
	* @param list
	* @param filterFields
	* @param clazz
	* @return
	* @throws InstantiationException
	* @throws IllegalAccessException
	* @throws NoSuchMethodException
	* @throws SecurityException
	* @throws IllegalArgumentException
	* @throws InvocationTargetException
	*/
	public List getFieldFilterList(List list,String filterFields,Class clazz)
	throws InstantiationException,IllegalAccessException, 
	NoSuchMethodException, SecurityException, 
	IllegalArgumentException, InvocationTargetException {
		List tempList = new ArrayList<>();
		if(list.size()<=0){
			return tempList;
		}
		if(filterFields==null||filterFields.trim().equals("")){
			return tempList;
		}
		//获取字段数组
		Field[] fields = clazz.getDeclaredFields();
		for (int i=0;i userList = new ArrayList<>();
		EzsGoods good01 = new EzsGoods();
		EzsGoods good02 = new EzsGoods();
		EzsGoods good03 = new EzsGoods();
		good01.setName("zhang001");
		good01.setAddess("河南");
		good01.setAddtime(new Date());
		good02.setName("zhang002");
		good02.setAddess("北京");
		good02.setAddtime(new Date());
		good03.setName("zhang003");
		good03.setAddess("罗亚");
		good03.setAddtime(new Date());
		userList.add(good01);
		userList.add(good02);
		userList.add(good03);
		
		FieldFilterUtil fieldFilterUtil = new FieldFilterUtil<>();
		String filterFields = "name,addess,addtime";
		//String filterFields = "name";
		try {
			List ulist = 
              fieldFilterUtil.getFieldFilterList(userList, filterFields, EzsGoods.class);
			for (EzsGoods ezsGoods : ulist) {
				System.out.println("过滤的结果:"+ezsGoods);
			}
		}catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

你可能感兴趣的:(Java基础)