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