1 package com.thoughtworks.xstream.converters.reflection; 2 3 import java.lang.reflect.Field ; 4 import java.lang.reflect.Modifier ; 5 import java.util.Iterator ; 6 7 16 public class PureJavaReflectionProvider implements ReflectionProvider { 17 18 protected FieldDictionary fieldDictionary = new FieldDictionary(); 19 20 public Object newInstance(Class type) { 21 try { 22 return type.newInstance(); 23 } catch (InstantiationException e) { 24 throw new ObjectAccessException("Cannot construct " + type.getName(), e); 25 } catch (IllegalAccessException e) { 26 throw new ObjectAccessException("Cannot construct " + type.getName(), e); 27 } 28 } 29 30 public void visitSerializableFields(Object object, ReflectionProvider.Visitor visitor) { 31 for (Iterator iterator = fieldDictionary.serializableFieldsFor(object.getClass()); iterator.hasNext();) { 32 Field field = (Field ) iterator.next(); 33 if (!fieldModifiersSupported(field)) { 34 continue; 35 } 36 validateFieldAccess(field); 37 Object value = null; 38 try { 39 value = field.get(object); 40 } catch (IllegalArgumentException e) { 41 throw new ObjectAccessException("Could not get field " + field.getClass() + "." + field.getName(), e); 42 } catch (IllegalAccessException e) { 43 throw new ObjectAccessException("Could not get field " + field.getClass() + "." + field.getName(), e); 44 } 45 visitor.visit(field.getName(), field.getType(), field.getDeclaringClass(), value); 46 } 47 } 48 49 public void writeField(Object object, String fieldName, Object value, Class definedIn) { 50 Field field = fieldDictionary.field(object.getClass(), fieldName, definedIn); 51 validateFieldAccess(field); 52 try { 53 field.set(object, value); 54 } catch (IllegalArgumentException e) { 55 throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e); 56 } catch (IllegalAccessException e) { 57 throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e); 58 } 59 } 60 61 public Class getFieldType(Object object, String fieldName, Class definedIn) { 62 return fieldDictionary.field(object.getClass(), fieldName, definedIn).getType(); 63 } 64 65 protected boolean fieldModifiersSupported(Field field) { 66 return !(Modifier.isStatic(field.getModifiers()) 67 || Modifier.isTransient(field.getModifiers())); 68 } 69 70 protected void validateFieldAccess(Field field) { 71 if (Modifier.isFinal(field.getModifiers())) { 72 throw new ObjectAccessException("Invalid final field " 73 + field.getDeclaringClass().getName() + "." + field.getName()); 74 } 75 } 76 77 } 78 | Popular Tags |