This repository was archived by the owner on Feb 26, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathAPTCodeModelHelper.java
More file actions
369 lines (298 loc) · 11.9 KB
/
Copy pathAPTCodeModelHelper.java
File metadata and controls
369 lines (298 loc) · 11.9 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/**
* Copyright (C) 2010-2013 eBusiness Information, Excilys 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 org.androidannotations.helper;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.ElementFilter;
import org.androidannotations.holder.EComponentHolder;
import org.androidannotations.holder.GeneratedClassHolder;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldRef;
import com.sun.codemodel.JFormatter;
import com.sun.codemodel.JInvocation;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JStatement;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
public class APTCodeModelHelper {
public JClass typeMirrorToJClass(TypeMirror type, GeneratedClassHolder holder) {
if (type instanceof DeclaredType) {
DeclaredType declaredType = (DeclaredType) type;
String declaredTypeName = declaredType.asElement().toString();
JClass declaredClass = holder.refClass(declaredTypeName);
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
List<JClass> typeArgumentJClasses = new ArrayList<JClass>();
for (TypeMirror typeArgument : typeArguments) {
typeArgumentJClasses.add(typeMirrorToJClass(typeArgument, holder));
}
if (typeArgumentJClasses.size() > 0) {
declaredClass = declaredClass.narrow(typeArgumentJClasses);
}
return declaredClass;
} else if (type instanceof WildcardType) {
// TODO : At his time (01/2013), it is not possible to handle the
// super bound because code model does not offer a way to model
// statement like " ? super X"
// (see http://java.net/jira/browse/CODEMODEL-11)
WildcardType wildcardType = (WildcardType) type;
TypeMirror extendsBound = wildcardType.getExtendsBound();
if (extendsBound == null) {
return holder.classes().OBJECT.wildcard();
} else {
return typeMirrorToJClass(extendsBound, holder).wildcard();
}
} else if (type instanceof ArrayType) {
ArrayType arrayType = (ArrayType) type;
JClass refClass = typeMirrorToJClass(arrayType.getComponentType(), holder);
return refClass.array();
} else {
return holder.refClass(type.toString());
}
}
public static class Parameter {
public final String name;
public final JClass jClass;
public Parameter(String name, JClass jClass) {
this.name = name;
this.jClass = jClass;
}
}
public JMethod overrideAnnotatedMethod(ExecutableElement executableElement, GeneratedClassHolder holder) {
String methodName = executableElement.getSimpleName().toString();
JClass returnType = typeMirrorToJClass(executableElement.getReturnType(), holder);
List<Parameter> parameters = new ArrayList<Parameter>();
for (VariableElement parameter : executableElement.getParameters()) {
String parameterName = parameter.getSimpleName().toString();
JClass parameterClass = typeMirrorToJClass(parameter.asType(), holder);
parameters.add(new Parameter(parameterName, parameterClass));
}
JMethod existingMethod = findAlreadyGeneratedMethod(holder.getGeneratedClass(), methodName, parameters);
if (existingMethod != null) {
return existingMethod;
}
JMethod method = holder.getGeneratedClass().method(JMod.PUBLIC, returnType, methodName);
method.annotate(Override.class);
for (VariableElement parameter : executableElement.getParameters()) {
String parameterName = parameter.getSimpleName().toString();
JClass parameterClass = typeMirrorToJClass(parameter.asType(), holder);
method.param(JMod.FINAL, parameterClass, parameterName);
}
for (TypeMirror superThrownType : executableElement.getThrownTypes()) {
JClass thrownType = typeMirrorToJClass(superThrownType, holder);
method._throws(thrownType);
}
for (TypeParameterElement typeParameter : executableElement.getTypeParameters()) {
List<? extends TypeMirror> bounds = typeParameter.getBounds();
JClass jClassBounds;
if (bounds.isEmpty()) {
jClassBounds = holder.classes().OBJECT;
} else {
// Currently Codemodel can't generate generics with multiple
// classes like this <T extends Number & Serializable>.
// So we only take the first class
jClassBounds = typeMirrorToJClass(bounds.get(0), holder);
}
method.generify(typeParameter.toString(), jClassBounds);
}
callSuperMethod(method, holder, method.body());
return method;
}
private JMethod findAlreadyGeneratedMethod(JDefinedClass definedClass, String methodName, List<Parameter> parameters) {
method: for (JMethod method : definedClass.methods()) {
if (method.name().equals(methodName) && method.params().size() == parameters.size()) {
int i = 0;
for (JVar param : method.params()) {
String searchedParamType = parameters.get(i).jClass.name();
if (!param.type().name().equals(searchedParamType)) {
continue method;
}
i++;
}
return method;
}
}
return null;
}
public void callSuperMethod(JMethod superMethod, GeneratedClassHolder holder, JBlock callBlock) {
JExpression activitySuper = holder.getGeneratedClass().staticRef("super");
JInvocation superCall = JExpr.invoke(activitySuper, superMethod);
for (JVar param : superMethod.params()) {
superCall.arg(param);
}
JType returnType = superMethod.type();
if (returnType.fullName().equals("void")) {
callBlock.add(superCall);
} else {
callBlock._return(superCall);
}
}
public JBlock removeBody(JMethod method) {
JBlock body = method.body();
try {
Field bodyField = JMethod.class.getDeclaredField("body");
bodyField.setAccessible(true);
bodyField.set(method, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
JBlock clonedBody = new JBlock(false, false);
for (Object statement : body.getContents()) {
if (statement instanceof JVar) {
JVar var = (JVar) statement;
try {
Field varInitField = JVar.class.getDeclaredField("init");
varInitField.setAccessible(true);
JExpression varInit = (JExpression) varInitField.get(var);
clonedBody.decl(var.type(), var.name(), varInit);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
clonedBody.add((JStatement) statement);
}
}
return clonedBody;
}
public void replaceSuperCall(JMethod method, JBlock replacement) {
String superCallStart = "super." + method.name() + "(";
JBlock oldBody = removeBody(method);
JBlock newBody = method.body();
for (Object content : oldBody.getContents()) {
StringWriter writer = new StringWriter();
JFormatter formatter = new JFormatter(writer);
JStatement statement = (JStatement) content;
statement.state(formatter);
String statementString = writer.getBuffer().toString();
if (statementString.startsWith(superCallStart)) {
newBody.add(replacement);
} else {
newBody.add(statement);
}
}
}
public String getIdStringFromIdFieldRef(JFieldRef idRef) {
try {
Field nameField = JFieldRef.class.getDeclaredField("name");
nameField.setAccessible(true);
String name = (String) nameField.get(idRef);
if (name != null) {
return name;
}
Field varField = JFieldRef.class.getDeclaredField("var");
varField.setAccessible(true);
JVar var = (JVar) varField.get(idRef);
if (var != null) {
return var.name();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new IllegalStateException("Unable to extract target name from JFieldRef");
}
public JDefinedClass createDelegatingAnonymousRunnableClass(EComponentHolder holder, JMethod delegatedMethod) {
JCodeModel codeModel = holder.codeModel();
JDefinedClass anonymousRunnableClass;
JBlock previousMethodBody = removeBody(delegatedMethod);
anonymousRunnableClass = codeModel.anonymousClass(Runnable.class);
JMethod runMethod = anonymousRunnableClass.method(JMod.PUBLIC, codeModel.VOID, "run");
runMethod.annotate(Override.class);
runMethod.body().add(previousMethodBody);
return anonymousRunnableClass;
}
/**
* Gets all of the methods of the class and includes the methods of any
* implemented interfaces.
*
* @param typeElement
* @return full list of methods.
*/
public List<ExecutableElement> getMethods(TypeElement typeElement) {
List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
List<ExecutableElement> methods = new ArrayList<ExecutableElement>(ElementFilter.methodsIn(enclosedElements));
// Add methods of the interfaces. These will be valid as they have gone
// through the validator.
for (TypeMirror iface : typeElement.getInterfaces()) {
DeclaredType dt = (DeclaredType) iface;
methods.addAll(ElementFilter.methodsIn(dt.asElement().getEnclosedElements()));
}
return methods;
}
public JMethod implementMethod(GeneratedClassHolder holder, List<ExecutableElement> methods, String methodName, String returnType, String... parameterTypes) {
// First get the ExecutableElement method object from the util function.
ExecutableElement method = getMethod(methods, methodName, returnType, parameterTypes);
JMethod jmethod = null;
if (method != null) {
// Get the return type or VOID if none.
JType jcReturnType = returnType.equals(TypeKind.VOID.toString()) ? holder.codeModel().VOID : holder.refClass(returnType);
// Create the implementation and annotate it with the Override
// annotation.
jmethod = holder.getGeneratedClass().method(JMod.PUBLIC, jcReturnType, method.getSimpleName().toString());
jmethod.annotate(Override.class);
// Create the parameters.
for (int i = 0; i < method.getParameters().size(); i++) {
VariableElement param = method.getParameters().get(i);
jmethod.param(holder.refClass(parameterTypes[i]), param.getSimpleName().toString());
}
}
return jmethod;
}
private ExecutableElement getMethod(List<ExecutableElement> methods, String methodName, String returnType, String... parameterTypes) {
for (ExecutableElement method : methods) {
List<? extends VariableElement> parameters = method.getParameters();
// Get the method return type or "VOID" if none.
String methodReturnType = method.getReturnType().getKind() == TypeKind.VOID ? TypeKind.VOID.toString() : method.getReturnType().toString();
if (parameters.size() == parameterTypes.length && methodReturnType.equals(returnType)) {
if (methodName == null || method.getSimpleName().toString().equals(methodName)) {
// At this point, method name, return type and number of
// parameters are correct. Now we need to validate the
// parameter types.
boolean validMethod = true;
for (int i = 0; i < parameters.size(); i++) {
VariableElement param = parameters.get(i);
if (!param.asType().toString().equals(parameterTypes[i])) {
// Parameter type does not match, this is not the
// correct method.
validMethod = false;
break;
}
}
if (validMethod) {
return method;
}
}
}
}
return null;
}
}