01: package org.drools.objenesis.instantiator.basic;
02:
03: import java.io.ObjectStreamClass;
04: import java.lang.reflect.Method;
05:
06: import org.drools.objenesis.ObjenesisException;
07: import org.drools.objenesis.instantiator.ObjectInstantiator;
08:
09: /**
10: * Instantiates a class by using reflection to make a call to private method
11: * ObjectStreamClass.newInstance, present in many JVM implementations. This instantiator will create
12: * classes in a way compatible with serialization, calling the first non-serializable superclass'
13: * no-arg constructor.
14: *
15: * @author Leonardo Mesquita
16: * @see ObjectInstantiator
17: * @see java.io.Serializable
18: */
19: public class ObjectStreamClassInstantiator implements
20: ObjectInstantiator {
21:
22: private static Method newInstanceMethod;
23:
24: private static void initialize() {
25: if (newInstanceMethod == null) {
26: try {
27: newInstanceMethod = ObjectStreamClass.class
28: .getDeclaredMethod("newInstance",
29: new Class[] {});
30: newInstanceMethod.setAccessible(true);
31: } catch (final Exception e) {
32: throw new ObjenesisException(e);
33: }
34: }
35: }
36:
37: private ObjectStreamClass objStreamClass;
38:
39: public ObjectStreamClassInstantiator(final Class type) {
40: initialize();
41: this .objStreamClass = ObjectStreamClass.lookup(type);
42: }
43:
44: public Object newInstance() {
45:
46: try {
47: return newInstanceMethod.invoke(this .objStreamClass,
48: new Object[] {});
49: } catch (final Exception e) {
50: throw new ObjenesisException(e);
51: }
52:
53: }
54:
55: }
|