KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tctest > performance > simulate > type > SimulatedTypeFactory


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tctest.performance.simulate.type;
5
6 import java.lang.reflect.Constructor JavaDoc;
7 import java.util.Collection JavaDoc;
8 import java.util.Collections JavaDoc;
9 import java.util.HashMap JavaDoc;
10 import java.util.Map JavaDoc;
11
12 public final class SimulatedTypeFactory {
13
14   private static final Map JavaDoc SIM_TYPES = Collections.synchronizedMap(new HashMap JavaDoc());
15   static {
16     SIM_TYPES.put(String JavaDoc.class.getName(), SimulatedPrimitiveType.class);
17     SIM_TYPES.put(Integer JavaDoc.class.getName(), SimulatedPrimitiveType.class);
18     SIM_TYPES.put(Long JavaDoc.class.getName(), SimulatedPrimitiveType.class);
19     SIM_TYPES.put(Collection JavaDoc.class.getName(), SimulatedCollection.class);
20     SIM_TYPES.put(Map JavaDoc.class.getName(), SimulatedMap.class);
21   }
22
23   private SimulatedTypeFactory() {
24     // cannot instantiate
25
}
26
27   public static SimulatedType create(Object JavaDoc obj) {
28     Constructor JavaDoc[] constructor = resolveSimType(obj).getDeclaredConstructors();
29     try {
30       return (SimulatedType) constructor[0].newInstance(new Object JavaDoc[] { obj });
31     } catch (Exception JavaDoc e) {
32       throw new RuntimeException JavaDoc(e);
33     }
34   }
35
36   private static Class JavaDoc resolveSimType(Object JavaDoc obj) {
37     Class JavaDoc simType = (Class JavaDoc) SIM_TYPES.get(obj.getClass().getName());
38     if (simType != null) return simType;
39
40     simType = resolveInterface(obj.getClass());
41     if (simType != null) return simType;
42
43     throw new RuntimeException JavaDoc("Type not supported: " + obj.getClass().getName());
44   }
45
46   private static Class JavaDoc resolveInterface(Class JavaDoc clazz) {
47     Class JavaDoc simType = null;
48     Class JavaDoc[] interfaces = clazz.getInterfaces();
49     for (int i = 0; i < interfaces.length; i++) {
50       simType = (Class JavaDoc) SIM_TYPES.get(interfaces[i].getName());
51       if (simType != null) return simType;
52       simType = resolveInterface(interfaces[i]);
53       if (simType != null) return simType;
54     }
55     return null;
56   }
57 }
58
Popular Tags