1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package com.codebox.builders;
16
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import javassist.CannotCompileException;
21 import javassist.ClassPool;
22 import javassist.CtClass;
23 import javassist.CtField;
24 import javassist.CtMethod;
25 import javassist.NotFoundException;
26
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30
31
32
33
34
35
36
37
38
39
40 public class ExtensionBuilder<T> {
41
42
43 private static final Logger logger = LoggerFactory.getLogger(ExtensionBuilder.class);
44
45
46
47
48
49
50
51
52
53
54
55
56 public Class<?> generate(final Class<T> clazz) throws NotFoundException, CannotCompileException {
57 try {
58
59 return Class.forName(clazz.getName() + "Extension");
60 } catch (final ClassNotFoundException e) {
61
62 ExtensionBuilder.logger.trace("No extension exists, so create it", e);
63 }
64
65 final ClassPool pool = ClassPool.getDefault();
66 final CtClass cc = pool.makeClass(clazz.getName() + "Extension");
67
68
69 cc.setSuperclass(ExtensionBuilder.resolveCtClass(clazz));
70
71 final Map<String, Class<?>> properties = new HashMap<>();
72 properties.put("jbExtension1", String.class);
73 properties.put("jbExtension2", String.class);
74 properties.put("jbExtension3", String.class);
75 properties.put("jbExtension4", String.class);
76
77 for (final Entry<String, Class<?>> entry : properties.entrySet()) {
78
79
80 cc.addField(new CtField(ExtensionBuilder.resolveCtClass(entry.getValue()), entry.getKey(), cc));
81
82
83 cc.addMethod(ExtensionBuilder.generateGetter(cc, entry.getKey(), entry.getValue()));
84
85
86 cc.addMethod(ExtensionBuilder.generateSetter(cc, entry.getKey(), entry.getValue()));
87 }
88
89 return cc.toClass();
90 }
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 private static CtMethod generateGetter(final CtClass declaringClass, final String fieldName,
106 final Class<?> fieldClass) throws CannotCompileException {
107 String methodSrc = """
108 public %s get%s() {
109 return this.%s;
110 }
111 """.formatted(fieldClass.getName(), fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1),
112 fieldName);
113 return CtMethod.make(methodSrc, declaringClass);
114 }
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129 private static CtMethod generateSetter(final CtClass declaringClass, final String fieldName,
130 final Class<?> fieldClass) throws CannotCompileException {
131 String methodSrc = """
132 public void set%s(%s %s) {
133 this.%s = %s;
134 }
135 """.formatted(fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), fieldClass.getName(),
136 fieldName, fieldName, fieldName);
137 return CtMethod.make(methodSrc, declaringClass);
138 }
139
140
141
142
143
144
145
146
147
148
149 private static CtClass resolveCtClass(final Class<?> clazz) throws NotFoundException {
150 return ClassPool.getDefault().get(clazz.getName());
151 }
152
153 }