java 反射应用_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java 反射应用

java 反射应用

 2013/7/28 3:14:04  hw1287789687  程序员俱乐部  我要评论(0)
  • 摘要:java中反射的应用:1,获取指定类的所有成员变量,包括父类的成员变量:/****getallfield,includingfieldsinfather/superclass**@paramclazz*@return*/publicstaticList<Field>getAllFields(Classclazz){List<Field>fieldsList=newArrayList<Field>();//returnobjectif(clazz==null)
  • 标签:Java 应用 反射

java 中反射的应用:

?

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

class="java" name="code">/***
	 * 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

?

发表评论
用户名: 匿名