有个项目用到反射,记录一下

public class Operate {
	/**
	 * 使用条件 :inObj与outClass具有相同的属性
	 * @param inObj 包含有数据的对象
	 * @param outClass 需要返回对象的类型
	 * @return outClass类型的实例,该实例的属性值通过inObj赋值
	 */
	public Object getEntity(Object inObj, Class<Object> outClass) {
		try {
			//获取inObj的所有属性
			Field[] myfield = inObj.getClass().getFields();
			//创建需要返回对象的实例
			Object resultObj = outClass.newInstance();
			//循环调用resultObj的set方法实现对象间的赋值处理
			for (int i = 0; i < myfield.length; i++) {
				//获得inObj对象的属性名称,并将首字母大写
				StringBuffer fieldName = toFirstUpperCase(myfield[i].getName());
				//构造set方法的名字,如setXXX
				StringBuffer methodName = new StringBuffer("set").append(fieldName);
				//构造outClass需要使用的方法
				Method m = outClass.getDeclaredMethod(methodName.toString(), myfield[i].getType());
				//调用方法实现赋值
				m.invoke(resultObj, myfield[i].get(inObj));
			}
			//返回对象
			return resultObj;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param str 需要处理的字符串
	 * @return 将str首字母大写的结果
	 */
	public StringBuffer toFirstUpperCase(String str) {
		//获取第一个字符,并转换为大写
		StringBuffer first = new StringBuffer(str.substring(0, 1).toUpperCase());
		//获取其余的字符
		StringBuffer back = new StringBuffer(str.substring(1, str.length()));
		//合并字符串
		StringBuffer result = first.append(back);
		//返回结果
		return result;

	}
}

你可能感兴趣的:(反射)