阅读859 返回首页    go 京东网上商城


java 中反射的应用

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



最后更新:2017-04-03 16:48:44

  上一篇:go Android手机修改字体颜色大小的教程
  下一篇:go Android Studio安装使用教程\环境搭建\常见问题汇总