01: package org.drools.objenesis.instantiator.sun;
02:
03: import java.lang.reflect.Constructor;
04:
05: import org.drools.objenesis.ObjenesisException;
06: import org.drools.objenesis.instantiator.ObjectInstantiator;
07:
08: import sun.reflect.ReflectionFactory;
09:
10: /**
11: * Instantiates an object, WITHOUT calling it's constructor, using internal
12: * sun.reflect.ReflectionFactory - a class only available on JDK's that use Sun's 1.4 (or later)
13: * Java implementation. This is the best way to instantiate an object without any side effects
14: * caused by the constructor - however it is not available on every platform.
15: *
16: * @see ObjectInstantiator
17: */
18: public class SunReflectionFactoryInstantiator implements
19: ObjectInstantiator {
20:
21: private final Constructor mungedConstructor;
22:
23: public SunReflectionFactoryInstantiator(final Class type) {
24:
25: final ReflectionFactory reflectionFactory = ReflectionFactory
26: .getReflectionFactory();
27: Constructor javaLangObjectConstructor;
28:
29: try {
30: javaLangObjectConstructor = Object.class
31: .getConstructor((Class[]) null);
32: } catch (final NoSuchMethodException e) {
33: throw new Error(
34: "Cannot find constructor for java.lang.Object!");
35: }
36: this .mungedConstructor = reflectionFactory
37: .newConstructorForSerialization(type,
38: javaLangObjectConstructor);
39: this .mungedConstructor.setAccessible(true);
40: }
41:
42: public Object newInstance() {
43: try {
44: return this .mungedConstructor.newInstance((Object[]) null);
45: } catch (final Exception e) {
46: throw new ObjenesisException(e);
47: }
48: }
49: }
|