01: package org.drools.objenesis;
02:
03: import java.util.HashMap;
04: import java.util.Map;
05:
06: import org.drools.objenesis.instantiator.ObjectInstantiator;
07: import org.drools.objenesis.strategy.InstantiatorStrategy;
08:
09: /**
10: * Base class to extend if you want to have a class providing your own default strategy. Can also be
11: * instantiated directly.
12: *
13: * @author Henri Tremblay
14: */
15: public class ObjenesisBase implements Objenesis {
16:
17: /** Strategy used by this Objenesi implementation to create classes */
18: protected final InstantiatorStrategy strategy;
19:
20: /** Strategy cache. Key = Class, Value = InstantiatorStrategy */
21: protected Map cache;
22:
23: /**
24: * Constructor allowing to pick a strategy and using cache
25: *
26: * @param strategy Strategy to use
27: */
28: public ObjenesisBase(final InstantiatorStrategy strategy) {
29: this (strategy, true);
30: }
31:
32: /**
33: * Flexible constructor allowing to pick the strategy and if caching should be used
34: *
35: * @param strategy Strategy to use
36: * @param useCache If {@link ObjectInstantiator}s should be cached
37: */
38: public ObjenesisBase(final InstantiatorStrategy strategy,
39: final boolean useCache) {
40: if (strategy == null) {
41: throw new IllegalArgumentException(
42: "A strategy can't be null");
43: }
44: this .strategy = strategy;
45: this .cache = useCache ? new HashMap() : null;
46: }
47:
48: public String toString() {
49: return getClass().getName() + " using "
50: + this .strategy.getClass().getName()
51: + (this .cache == null ? " without" : " with")
52: + " caching";
53: }
54:
55: /**
56: * Will create a new object without any constructor being called
57: *
58: * @param clazz Class to instantiate
59: * @return New instance of clazz
60: */
61: public Object newInstance(final Class clazz) {
62: return getInstantiatorOf(clazz).newInstance();
63: }
64:
65: /**
66: * Will pick the best instantiator for the provided class. If you need to create a lot of
67: * instances from the same class, it is way more efficient to create them from the same
68: * ObjectInstantiator than calling {@link #newInstance(Class)}.
69: *
70: * @param clazz Class to instantiate
71: * @return Instantiator dedicated to the class
72: */
73: public synchronized ObjectInstantiator getInstantiatorOf(
74: final Class clazz) {
75: if (this .cache == null) {
76: return this .strategy.newInstantiatorOf(clazz);
77: }
78: ObjectInstantiator instantiator = (ObjectInstantiator) this.cache
79: .get(clazz.getName());
80: if (instantiator == null) {
81: instantiator = this.strategy.newInstantiatorOf(clazz);
82: this.cache.put(clazz.getName(), instantiator);
83: }
84: return instantiator;
85: }
86:
87: }
|