KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > javabean > BeanProvider


1 package com.thoughtworks.xstream.converters.javabean;
2
3 import java.lang.reflect.Constructor JavaDoc;
4 import java.lang.reflect.InvocationTargetException JavaDoc;
5 import java.lang.reflect.Modifier JavaDoc;
6 import java.util.Iterator JavaDoc;
7
8 import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
9
10 /**
11  * Pure Java ObjectFactory that instantiates objects using standard Java
12  * reflection, however the types of objects that can be constructed are limited.
13  * <p/>Can newInstance: classes with public visibility, outer classes, static
14  * inner classes, classes with default constructors and any class that
15  * implements java.io.Serializable. Cannot newInstance: classes without public
16  * visibility, non-static inner classes, classes without default constructors.
17  * Note that any code in the constructor of a class will be executed when the
18  * ObjectFactory instantiates the object.
19  * </p>
20  */

21 public class BeanProvider {
22
23 // private final Map serializedDataCache = Collections.synchronizedMap(new HashMap());
24
//
25
protected PropertyDictionary propertyDictionary = new PropertyDictionary();
26     
27     protected static final Object JavaDoc[] NO_PARAMS = new Object JavaDoc[0];
28
29     public Object JavaDoc newInstance(Class JavaDoc type) {
30         try {
31             return getDefaultConstrutor(type).newInstance(NO_PARAMS);
32         } catch (InstantiationException JavaDoc e) {
33             throw new ObjectAccessException("Cannot construct " + type.getName(), e);
34         } catch (IllegalAccessException JavaDoc e) {
35             throw new ObjectAccessException("Cannot construct " + type.getName(), e);
36         } catch (InvocationTargetException JavaDoc e) {
37             if (e.getTargetException() instanceof RuntimeException JavaDoc) {
38                 throw (RuntimeException JavaDoc) e.getTargetException();
39             } else if (e.getTargetException() instanceof Error JavaDoc) {
40                 throw (Error JavaDoc) e.getTargetException();
41             } else {
42                 throw new ObjectAccessException("Constructor for " + type.getName()
43                         + " threw an exception", e);
44             }
45         }
46     }
47
48 // private Object instantiateUsingSerialization(Class type) {
49
// try {
50
// byte[] data;
51
// if (serializedDataCache.containsKey(type)) {
52
// data = (byte[]) serializedDataCache.get(type);
53
// } else {
54
// ByteArrayOutputStream bytes = new ByteArrayOutputStream();
55
// DataOutputStream stream = new DataOutputStream(bytes);
56
// stream.writeShort(ObjectStreamConstants.STREAM_MAGIC);
57
// stream.writeShort(ObjectStreamConstants.STREAM_VERSION);
58
// stream.writeByte(ObjectStreamConstants.TC_OBJECT);
59
// stream.writeByte(ObjectStreamConstants.TC_CLASSDESC);
60
// stream.writeUTF(type.getName());
61
// stream.writeLong(ObjectStreamClass.lookup(type).getSerialVersionUID());
62
// stream.writeByte(2); // classDescFlags (2 = Serializable)
63
// stream.writeShort(0); // field count
64
// stream.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA);
65
// stream.writeByte(ObjectStreamConstants.TC_NULL);
66
// data = bytes.toByteArray();
67
// serializedDataCache.put(type, data);
68
// }
69
//
70
// ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
71
// return in.readObject();
72
// } catch (IOException e) {
73
// throw new ObjectAccessException("", e);
74
// } catch (ClassNotFoundException e) {
75
// throw new ObjectAccessException("", e);
76
// }
77
// }
78

79     public void visitSerializableProperties(Object JavaDoc object, Visitor visitor) {
80         for (Iterator JavaDoc iterator = propertyDictionary.serializablePropertiesFor(object.getClass()); iterator
81                 .hasNext();) {
82             BeanProperty property = (BeanProperty) iterator.next();
83             Object JavaDoc value = null;
84             try {
85                 value = property.get(object);
86             } catch (IllegalArgumentException JavaDoc e) {
87                 throw new ObjectAccessException("Could not get property " + property.getClass()
88                         + "." + property.getName(), e);
89             } catch (IllegalAccessException JavaDoc e) {
90                 throw new ObjectAccessException("Could not get property " + property.getClass()
91                         + "." + property.getName(), e);
92             }
93             visitor.visit(property.getName(), property.getType(), value);
94         }
95     }
96
97     public void writeProperty(Object JavaDoc object, String JavaDoc propertyName, Object JavaDoc value) {
98         BeanProperty property = propertyDictionary.property(object.getClass(), propertyName);
99         try {
100             property.set(object, value);
101         } catch (IllegalArgumentException JavaDoc e) {
102             throw new ObjectAccessException("Could not set property " + object.getClass() + "."
103                     + property.getName(), e);
104         } catch (IllegalAccessException JavaDoc e) {
105             throw new ObjectAccessException("Could not set property " + object.getClass() + "."
106                     + property.getName(), e);
107         }
108     }
109
110     public Class JavaDoc getPropertyType(Object JavaDoc object, String JavaDoc name) {
111         return propertyDictionary.property(object.getClass(), name).getType();
112     }
113
114     public boolean propertyDefinedInClass(String JavaDoc name, Class JavaDoc type) {
115         return propertyDictionary.property(type, name) != null;
116     }
117
118     /**
119      * Returns true if the Bean provider can instantiate the specified class
120      */

121     public boolean canInstantiate(Class JavaDoc type) {
122         return getDefaultConstrutor(type) != null;
123     }
124     
125     /**
126      * Returns the default constructor, or null if none is found
127      * @param type
128      * @return
129      */

130     protected Constructor JavaDoc getDefaultConstrutor(Class JavaDoc type) {
131         Constructor JavaDoc[] constructors = type.getConstructors();
132         for (int i = 0; i < constructors.length; i++) {
133             Constructor JavaDoc c = constructors[i];
134             if (c.getParameterTypes().length == 0 && Modifier.isPublic(c.getModifiers()))
135                 return c;
136         }
137         return null;
138     }
139     
140     interface Visitor {
141         void visit(String JavaDoc name, Class JavaDoc type, Object JavaDoc value);
142     }
143
144 }
Popular Tags