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