01: /*
02: * Created by IntelliJ IDEA.
03: * User: sg426575
04: * Date: May 20, 2006
05: * Time: 6:05:05 AM
06: */
07: package com.technoetic.xplanner.util;
08:
09: import java.util.Map;
10: import java.util.List;
11: import java.util.ArrayList;
12: import java.util.HashMap;
13: import java.lang.reflect.Field;
14:
15: public class ClassUtil {
16: public static Object getFieldValue(Object object, String fieldName)
17: throws Exception {
18: Field field = getField(object, fieldName);
19: field.setAccessible(true);
20: return field.get(object);
21: }
22:
23: public static void setFieldValue(Object object, String fieldName,
24: Object value) throws Exception {
25: Field field = getField(object, fieldName);
26: field.setAccessible(true);
27: field.set(object, value);
28: }
29:
30: private static Field getField(Object object, String fieldName)
31: throws NoSuchFieldException {
32: Map allFields = getAllFieldByNames(object.getClass());
33: Field field = (Field) allFields.get(fieldName);
34: if (field == null)
35: throw new NoSuchFieldException(fieldName
36: + " is not a field of " + object.getClass());
37: return field;
38: }
39:
40: public static List getAllFieldNames(Object object) throws Exception {
41: Map allFields = getAllFieldByNames(object.getClass());
42: return new ArrayList(allFields.keySet());
43: }
44:
45: public static List getAllFields(Object object) throws Exception {
46: Map allFields = getAllFieldByNames(object.getClass());
47: return new ArrayList(allFields.values());
48: }
49:
50: public static Map getAllFieldByNames(Class theClass) {
51: Map fields;
52: Class super class = theClass.getSuperclass();
53: if (super class != Object.class) {
54: fields = getAllFieldByNames(super class);
55: } else
56: fields = new HashMap();
57: fields.putAll(getClassFieldByNames(theClass));
58: return fields;
59: }
60:
61: private static Map getClassFieldByNames(Class theClass) {
62: Field[] fields = theClass.getDeclaredFields();
63: Map fieldNames = new HashMap(fields.length);
64: for (int i = 0; i < fields.length; i++) {
65: Field field = fields[i];
66: field.setAccessible(true);
67: fieldNames.put(field.getName(), field);
68: }
69: return fieldNames;
70: }
71:
72: }
|