java 反射应用

236 篇文章 0 订阅

java 中反射的应用:

 

1,获取指定类的所有成员变量,包括父类的成员变量:

/***
	 * get all field ,including fields in father/super class
	 * 
	 * @param clazz
	 * @return
	 */
	public static List<Field> getAllFields(Class clazz) {
		List<Field> fieldsList = new ArrayList<Field>();// return object
		if (clazz == null) {
			return null;
		}

		Class superClass = clazz.getSuperclass();// father class
		if (superClass.getName().equals(Object.class.getName()))/*
																 * java.lang.Object
																 */{
			// System.out.println("no father");
		} else {
			// System.out.println("has father");
			fieldsList.addAll(getAllFields(superClass));// Recursive
		}

		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			fieldsList.add(field);
		}

		return fieldsList;
	}

 2,设置指定属性(私有成员变量)的值

/***
	 * 
	 * @param obj
	 * @param propertyName
	 *            : property name
	 * @param propertyValue
	 *            : value of property
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void setObjectValue(Object obj, String propertyName,
			String propertyValue) throws SecurityException,
			NoSuchFieldException, IllegalArgumentException,
			IllegalAccessException {
		if (StringUtils.isEmpty(propertyName)
				|| StringUtils.isEmpty(propertyValue)) {
			return;
		}
		Class<?> clazz = obj.getClass();
		Field name = clazz.getDeclaredField(propertyName);
		name.setAccessible(true);
		name.set(obj, propertyValue);

	}

 

 

3,获取指定属性(私有成员变量)的值

/***
	 * 
	 * @param obj
	 * @param propertyName  :name of property 
	 * @return
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static Object getObjectValue(Object obj, String propertyName)
			throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {
		if (StringUtils.isEmpty(propertyName)) {
			return null;
		}
		Class<?> clazz = obj.getClass();
		Field name = clazz.getDeclaredField(propertyName);
		name.setAccessible(true);
		return name.get(obj);
	}

 说明:依赖的jar:commons-lang-2.6.jar

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值