/
ClassGenerator.java
330 lines (290 loc) · 11.7 KB
/
ClassGenerator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
* Copyright 1999-2011 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.common.bytecode;
import com.alibaba.dubbo.common.utils.ReflectUtils;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* ClassGenerator
*
* @author qian.lei
*/
public final class ClassGenerator {
private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0);
private static final String SIMPLE_NAME_TAG = "<init>";
private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<ClassLoader, ClassPool>(); //ClassLoader - ClassPool
private ClassPool mPool;
private CtClass mCtc;
private String mClassName, mSuperClass;
private Set<String> mInterfaces;
private List<String> mFields, mConstructors, mMethods;
private Map<String, Method> mCopyMethods; // <method desc,method instance>
private Map<String, Constructor<?>> mCopyConstructors; // <constructor desc,constructor instance>
private boolean mDefaultConstructor = false;
private ClassGenerator() {
}
private ClassGenerator(ClassPool pool) {
mPool = pool;
}
public static ClassGenerator newInstance() {
return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader()));
}
public static ClassGenerator newInstance(ClassLoader loader) {
return new ClassGenerator(getClassPool(loader));
}
public static boolean isDynamicClass(Class<?> cl) {
return ClassGenerator.DC.class.isAssignableFrom(cl);
}
public static ClassPool getClassPool(ClassLoader loader) {
if (loader == null)
return ClassPool.getDefault();
ClassPool pool = POOL_MAP.get(loader);
if (pool == null) {
pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
POOL_MAP.put(loader, pool);
}
return pool;
}
private static String modifier(int mod) {
if (Modifier.isPublic(mod)) return "public";
if (Modifier.isProtected(mod)) return "protected";
if (Modifier.isPrivate(mod)) return "private";
return "";
}
public String getClassName() {
return mClassName;
}
public ClassGenerator setClassName(String name) {
mClassName = name;
return this;
}
public ClassGenerator addInterface(String cn) {
if (mInterfaces == null)
mInterfaces = new HashSet<String>();
mInterfaces.add(cn);
return this;
}
public ClassGenerator addInterface(Class<?> cl) {
return addInterface(cl.getName());
}
public ClassGenerator setSuperClass(String cn) {
mSuperClass = cn;
return this;
}
public ClassGenerator setSuperClass(Class<?> cl) {
mSuperClass = cl.getName();
return this;
}
public ClassGenerator addField(String code) {
if (mFields == null)
mFields = new ArrayList<String>();
mFields.add(code);
return this;
}
public ClassGenerator addField(String name, int mod, Class<?> type) {
return addField(name, mod, type, null);
}
public ClassGenerator addField(String name, int mod, Class<?> type, String def) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' ');
sb.append(name);
if (def != null && def.length() > 0) {
sb.append('=');
sb.append(def);
}
sb.append(';');
return addField(sb.toString());
}
public ClassGenerator addMethod(String code) {
if (mMethods == null)
mMethods = new ArrayList<String>();
mMethods.add(code);
return this;
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, String body) {
return addMethod(name, mod, rt, pts, null, body);
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, Class<?>[] ets, String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0)
sb.append(',');
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0)
sb.append(',');
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addMethod(sb.toString());
}
public ClassGenerator addMethod(Method m) {
addMethod(m.getName(), m);
return this;
}
public ClassGenerator addMethod(String name, Method m) {
String desc = name + ReflectUtils.getDescWithoutMethodName(m);
addMethod(':' + desc);
if (mCopyMethods == null)
mCopyMethods = new ConcurrentHashMap<String, Method>(8);
mCopyMethods.put(desc, m);
return this;
}
public ClassGenerator addConstructor(String code) {
if (mConstructors == null)
mConstructors = new LinkedList<String>();
mConstructors.add(code);
return this;
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, String body) {
return addConstructor(mod, pts, null, body);
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, Class<?>[] ets, String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0)
sb.append(',');
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0)
sb.append(',');
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addConstructor(sb.toString());
}
public ClassGenerator addConstructor(Constructor<?> c) {
String desc = ReflectUtils.getDesc(c);
addConstructor(":" + desc);
if (mCopyConstructors == null)
mCopyConstructors = new ConcurrentHashMap<String, Constructor<?>>(4);
mCopyConstructors.put(desc, c);
return this;
}
public ClassGenerator addDefaultConstructor() {
mDefaultConstructor = true;
return this;
}
public ClassPool getClassPool() {
return mPool;
}
public Class<?> toClass() {
return toClass(getClass().getClassLoader(), getClass().getProtectionDomain());
}
public Class<?> toClass(ClassLoader loader, ProtectionDomain pd) {
if (mCtc != null)
mCtc.detach();
long id = CLASS_NAME_COUNTER.getAndIncrement();
try {
CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass);
if (mClassName == null)
mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers())
? ClassGenerator.class.getName() : mSuperClass + "$sc") + id;
mCtc = mPool.makeClass(mClassName);
if (mSuperClass != null)
mCtc.setSuperclass(ctcs);
mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag.
if (mInterfaces != null)
for (String cl : mInterfaces) mCtc.addInterface(mPool.get(cl));
if (mFields != null)
for (String code : mFields) mCtc.addField(CtField.make(code, mCtc));
if (mMethods != null) {
for (String code : mMethods) {
if (code.charAt(0) == ':')
mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), code.substring(1, code.indexOf('(')), mCtc, null));
else
mCtc.addMethod(CtNewMethod.make(code, mCtc));
}
}
if (mDefaultConstructor)
mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc));
if (mConstructors != null) {
for (String code : mConstructors) {
if (code.charAt(0) == ':') {
mCtc.addConstructor(CtNewConstructor.copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null));
} else {
String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $.
mCtc.addConstructor(CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc));
}
}
}
return mCtc.toClass(loader, pd);
} catch (RuntimeException e) {
throw e;
} catch (NotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (CannotCompileException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public void release() {
if (mCtc != null) mCtc.detach();
if (mInterfaces != null) mInterfaces.clear();
if (mFields != null) mFields.clear();
if (mMethods != null) mMethods.clear();
if (mConstructors != null) mConstructors.clear();
if (mCopyMethods != null) mCopyMethods.clear();
if (mCopyConstructors != null) mCopyConstructors.clear();
}
private CtClass getCtClass(Class<?> c) throws NotFoundException {
return mPool.get(c.getName());
}
private CtMethod getCtMethod(Method m) throws NotFoundException {
return getCtClass(m.getDeclaringClass()).getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m));
}
private CtConstructor getCtConstructor(Constructor<?> c) throws NotFoundException {
return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c));
}
public static interface DC {
} // dynamic class tag interface.
}