01: package org.drools.objenesis.instantiator.sun;
02:
03: import java.io.NotSerializableException;
04: import java.lang.reflect.Constructor;
05:
06: import org.drools.objenesis.ObjenesisException;
07: import org.drools.objenesis.instantiator.ObjectInstantiator;
08: import org.drools.objenesis.instantiator.SerializationInstantiatorHelper;
09:
10: import sun.reflect.ReflectionFactory;
11:
12: /**
13: * Instantiates an object using internal sun.reflect.ReflectionFactory - a class only available on
14: * JDK's that use Sun's 1.4 (or later) Java implementation. This instantiator will create classes in
15: * a way compatible with serialization, calling the first non-serializable superclass' no-arg
16: * constructor. This is the best way to instantiate an object without any side effects caused by the
17: * constructor - however it is not available on every platform.
18: *
19: * @see ObjectInstantiator
20: */
21: public class SunReflectionFactorySerializationInstantiator implements
22: ObjectInstantiator {
23:
24: private final Constructor mungedConstructor;
25:
26: public SunReflectionFactorySerializationInstantiator(
27: final Class type) {
28:
29: final Class nonSerializableAncestor = SerializationInstantiatorHelper
30: .getNonSerializableSuperClass(type);
31: final ReflectionFactory reflectionFactory = ReflectionFactory
32: .getReflectionFactory();
33: Constructor nonSerializableAncestorConstructor;
34: try {
35: nonSerializableAncestorConstructor = nonSerializableAncestor
36: .getConstructor((Class[]) null);
37: } catch (final NoSuchMethodException e) {
38: /**
39: * @todo (Henri) I think we should throw a NotSerializableException just to put the same
40: * message a ObjectInputStream. Otherwise, the user won't know if the null returned
41: * if a "Not serializable", a "No default constructor on ancestor" or a "Exception in
42: * constructor"
43: */
44: throw new ObjenesisException(new NotSerializableException(
45: type + " has no suitable superclass constructor"));
46: }
47:
48: this .mungedConstructor = reflectionFactory
49: .newConstructorForSerialization(type,
50: nonSerializableAncestorConstructor);
51: this .mungedConstructor.setAccessible(true);
52: }
53:
54: public Object newInstance() {
55: try {
56: return this .mungedConstructor.newInstance((Object[]) null);
57: } catch (final Exception e) {
58: throw new ObjenesisException(e);
59: }
60: }
61: }
|