利用java的反射创建一个联合实体类

利用java中的method类中的方法进行封装,直接上代码:

public class ModelUtils {
	
	//需要一个List放置实体类
	List<Object> list=null;
	
	
	/**
	 * 构造函数,进行赋值
	 * @param list
	 */
	public ModelUtils(List<Object> list){
		this.list=list;
	}

	/**
	 * 获取属性的值
	 * @param fName  获取联合实体类的属性的名称
	 * @return
	 */
	public <T> T getValue(String fName){
		//组装方法名
		String methodName="get"+fName.substring(0,1).toUpperCase()+fName.substring(1);
		//获取方法名所在的实体类
		for(Object o:list){
			try {
				//查找方法
				Method method = o.getClass().getMethod(methodName);
				//判断方法是否存在
				if(method!=null){
					//由于invoke返回的是Object类型,因此要强制转换成T类型
					return (T)method.invoke(o);
				}				
			} catch (Exception e) {
			}
		}
		return null;
	}

	public <T> void setValue(String fName,T value,Class<T> type){
		String methodName="set"+fName.substring(0,1).toUpperCase()+fName.substring(1);
		for(Object o:list){
			try {
				//查找方法
				Method method = o.getClass().getMethod(methodName,type);
				if(method!=null){
					method.invoke(o, value);
					return;
				}
			} catch (Exception e) {
			}
		}
	}
}
测试类



猜你喜欢

转载自blog.csdn.net/hbl6016/article/details/53671054