java利用反射获取类属性名,获取JavaBean属性名

13 篇文章 0 订阅
/**
	 * 获取类属性名
	 * 
	 * @param pclass
	 * @return String[]
	 * @throws FrameException
	 */
	public static String[] getClassDeclaredFieldNames(Class<?> pclass) throws FrameException {
		Field[] propertyField;
		String[] returnArray;
		int count = 0;

		if (pclass == null) {
			return null;
		}
		propertyField = pclass.getDeclaredFields();
		if (propertyField != null && propertyField.length > 0) {
			count = propertyField.length;
		}

		returnArray = new String[count];
		for (int i = 0; i < count; i++) {
			returnArray[i] = propertyField[i].getName();
		}
		return returnArray;
	}

	/**
	 * 获取JavaBean属性名
	 * 
	 * @param pclass
	 * @return String[]
	 * @throws FrameException
	 */
	public static ObjectFieldDescriptor[] getObjectFieldDescriptors(Object obj) throws FrameException {
		Field[] fields;
		Field field;
		int count = 0;
		ObjectFieldDescriptor[] objectFieldDescriptors;
		String name;
		Object value;

		if (obj == null) {
			return null;
		}
		fields = obj.getClass().getDeclaredFields();
		if (fields != null && fields.length > 0) {
			count = fields.length;
		}
		objectFieldDescriptors = new ObjectFieldDescriptor[count];

		for (int i = 0; i < count; i++) {
			field = fields[i];
			name = field.getName();
			value = getFieldValueIgnoreAccessible(obj, field);

			objectFieldDescriptors[i] = new ObjectFieldDescriptor(name, field.getType(), value);

		}
		return objectFieldDescriptors;
	}
/**
	 * 获取对象的域值,忽略访问权限
	 * 
	 * @throws FrameException
	 */
	public static Object getFieldValueIgnoreAccessible(Object obj, Field field) throws FrameException {
		boolean accessible;
		Object value;

		if (obj == null) {
			throw new FrameException("传入参数[obj]为空!");
		}
		if (field == null) {
			throw new FrameException("传入参数[field]为空!");
		}

		try {
			accessible = field.isAccessible();
			if (!accessible) {
				field.setAccessible(true);
			}
			value = field.get(obj);
			field.setAccessible(accessible);
			return value;
		} catch (IllegalArgumentException e) {
			throw new FrameException(e);
		} catch (IllegalAccessException e) {
			throw new FrameException(e);
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值