1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.ep.db4o.javassist;
18
19 import java.lang.reflect.Field;
20
21 import net.ep.db4o.factories.InvalidFactoryException;
22 import net.ep.db4o.factories.ObjectContainerProvider;
23
24 import com.db4o.ObjectContainer;
25 import com.db4o.reflect.generic.GenericReflector;
26 import com.db4o.reflect.jdk.JavaReflectClass;
27
28 public class Enhancer {
29
30 @SuppressWarnings("unchecked")
31 public static <T> Class<T> enhancedClass(Class<T> targetType,
32 ObjectContainerProvider _provider) {
33 ObjectContainer db = _provider.db();
34 if (db == null)
35 throw new NullPointerException(ObjectContainerProvider.class.getName() + " returned a null result");
36 GenericReflector refl = db.ext().reflector();
37 if (refl.getDelegate() instanceof JVSTReflector) {
38 JVSTReflector reflector = (JVSTReflector) _provider.db().ext().reflector()
39 .getDelegate();
40
41 if (JVSTReflector.canBeEnhanced(targetType)) {
42 JVSTClass enhClazz1 = reflector.enhanceClass(targetType);
43 return enhClazz1.getEnhancedClass();
44 } else
45 throw new InvalidFactoryException(targetType + " cannot be enhanced: "
46 + JVSTReflector.explainWhyNotEnhanced(targetType));
47 }
48 return targetType;
49 }
50
51 @SuppressWarnings("unchecked")
52 public static <T> T newInstance(Class<T> clazz, ObjectContainer container) {
53 GenericReflector refl = container.ext().reflector();
54 if (refl.getDelegate() instanceof JVSTReflector) {
55 JVSTReflector reflector = (JVSTReflector) container.ext().reflector()
56 .getDelegate();
57
58 JavaReflectClass enhClazz1 = (JavaReflectClass) reflector.forClass(clazz);
59 T copy = (T) enhClazz1.newInstance();
60 container.store(copy);
61 return copy;
62 }
63 try {
64 return clazz.newInstance();
65 } catch (Exception e) {
66 e.printStackTrace();
67 return null;
68 }
69 }
70
71 @SuppressWarnings("unchecked")
72 public static <T> T enhance(T input, ObjectContainer container) {
73 Class clazz = input.getClass();
74 T output = (T) newInstance(clazz, container);
75 if (output == null)
76 return null;
77 try {
78 cloneFrom(clazz, input, output);
79 } catch (Exception e) {
80 e.printStackTrace();
81 return null;
82 }
83 return output;
84 }
85
86 public static <T> void cloneFrom(T input, T output)
87 throws IllegalArgumentException, IllegalAccessException {
88 cloneFrom(input.getClass(), input, output);
89 }
90
91 @SuppressWarnings("unchecked")
92 private static <T> void cloneFrom(Class cl, T input, T output)
93 throws IllegalArgumentException, IllegalAccessException {
94 for (Field field : cl.getDeclaredFields()) {
95 boolean acc = field.isAccessible();
96 field.setAccessible(true);
97 field.set(output, field.get(input));
98 field.setAccessible(acc);
99 }
100 if (cl.getSuperclass() != null)
101 cloneFrom(cl.getSuperclass(), input, output);
102 }
103
104 }