use of com.squareup.javapoet.ParameterSpec in project EasyRouter by Xiasm.
the class InterceptorProcessor method parseInterceptor.
/**
* 解析拦截器
*
* @author luoxiaohui
* @createTime 2019-05-23 20:12
*/
private void parseInterceptor(Set<? extends Element> elements) throws IOException {
if (!Utils.isEmpty(elements)) {
for (Element element : elements) {
if (verify(element)) {
Interceptor interceptor = element.getAnnotation(Interceptor.class);
interceptors.put(interceptor.priority(), element);
}
}
TypeElement iInterceptor = elementUtils.getTypeElement(Constant.IINTERCEPTOR);
TypeElement iInterceptorGroup = elementUtils.getTypeElement(Constant.IINTERCEPTOR_GROUP);
/**
* Map<String, Class<? extends IInterceptor></>>
*/
ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(Integer.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(iInterceptor))));
/**
* 参数+变量名
* Map<String, Class<? extends IInterceptor>> interceptors
*/
ParameterSpec parameterSpec = ParameterSpec.builder(parameterizedTypeName, "interceptors").build();
/**
* 构建方法
* public void loadInto(Map<String, Class<? extends IInterceptor>> interceptors){}
*/
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(Constant.METHOD_LOAD_INTO).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(parameterSpec);
if (!interceptors.isEmpty() && interceptors.size() > 0) {
/**
* 构建方法体中的语句
*/
for (Map.Entry<Integer, Element> entry : interceptors.entrySet()) {
methodBuilder.addStatement("interceptors.put(" + entry.getKey() + ", $T.class)", ClassName.get((TypeElement) entry.getValue()));
}
}
/**
* 将文件写入磁盘中
* 路径是在app/build/source/api/debug/PACKAGE_OF_GENERATE_FILE下面
*/
JavaFile.builder(Constant.PACKAGE_OF_GENERATE_FILE, TypeSpec.classBuilder(Constant.NAME_OF_INTERCEPTOR + moduleName).addModifiers(Modifier.PUBLIC).addMethod(methodBuilder.build()).addSuperinterface(ClassName.get(iInterceptorGroup)).build()).build().writeTo(filerUtils);
}
}
use of com.squareup.javapoet.ParameterSpec in project Rocket by mozilla-tw.
the class RequestBuilderGenerator method generateGeneratedRequestOptionEquivalent.
/**
* Generates a particular method with an equivalent name and arguments to the given method
* from the generated {@link com.bumptech.glide.request.BaseRequestBuilder} subclass.
*/
private MethodSpec generateGeneratedRequestOptionEquivalent(MethodSpec requestOptionMethod) {
CodeBlock callRequestOptionsMethod = CodeBlock.builder().add(".$N(", requestOptionMethod.name).add(FluentIterable.from(requestOptionMethod.parameters).transform(new Function<ParameterSpec, String>() {
@Override
public String apply(ParameterSpec input) {
return input.name;
}
}).join(Joiner.on(", "))).add(");\n").build();
MethodSpec.Builder result = MethodSpec.methodBuilder(requestOptionMethod.name).addJavadoc(processorUtil.generateSeeMethodJavadoc(requestOptionsClassName, requestOptionMethod)).addModifiers(Modifier.PUBLIC).varargs(requestOptionMethod.varargs).addAnnotations(FluentIterable.from(requestOptionMethod.annotations).filter(new Predicate<AnnotationSpec>() {
@Override
public boolean apply(AnnotationSpec input) {
return !input.type.equals(TypeName.get(Override.class)) && // non-final to allow for mocking.
!input.type.equals(TypeName.get(SafeVarargs.class)) && // autoClone() in RequestBuilder.
!input.type.equals(CHECK_RESULT_CLASS_NAME);
}
}).toList()).addTypeVariables(requestOptionMethod.typeVariables).addParameters(requestOptionMethod.parameters).returns(generatedRequestBuilderOfTranscodeType).beginControlFlow("if (getMutableOptions() instanceof $T)", requestOptionsClassName).addCode("this.requestOptions = (($T) getMutableOptions())", requestOptionsClassName).addCode(callRequestOptionsMethod).nextControlFlow("else").addCode(CodeBlock.of("this.requestOptions = new $T().apply(this.requestOptions)", requestOptionsClassName)).addCode(callRequestOptionsMethod).endControlFlow().addStatement("return this");
if (requestOptionMethod.annotations.contains(AnnotationSpec.builder(SafeVarargs.class).build())) {
result.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").addMember("value", "$S", "varargs").build());
}
return result.build();
}
use of com.squareup.javapoet.ParameterSpec in project AndroidLife by CaMnter.
the class AutowiredProcessor method generateHelper.
/**
* 生成 ???$$ARouter$$Autowired 类
*
* @throws IOException IOException
* @throws IllegalAccessException IllegalAccessException
*/
private void generateHelper() throws IOException, IllegalAccessException {
TypeElement type_ISyringe = elements.getTypeElement(ISYRINGE);
TypeElement type_JsonService = elements.getTypeElement(JSON_SERVICE);
TypeMirror iProvider = elements.getTypeElement(Consts.IPROVIDER).asType();
TypeMirror activityTm = elements.getTypeElement(Consts.ACTIVITY).asType();
TypeMirror fragmentTm = elements.getTypeElement(Consts.FRAGMENT).asType();
TypeMirror fragmentTmV4 = elements.getTypeElement(Consts.FRAGMENT_V4).asType();
// Build input param name.
/**
* 生成 inject 方法参数
*
* @Override
* Object target
*/
ParameterSpec objectParamSpec = ParameterSpec.builder(TypeName.OBJECT, "target").build();
if (MapUtils.isNotEmpty(parentAndChild)) {
for (Map.Entry<TypeElement, List<Element>> entry : parentAndChild.entrySet()) {
// Build method : 'inject'
/**
* 生成 inject 方法
*
* @Override
* public void inject(Object target)
*/
MethodSpec.Builder injectMethodBuilder = MethodSpec.methodBuilder(METHOD_INJECT).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(objectParamSpec);
/**
* 每个 @Autowired 的 类 Element
* 每个 @Autowired 的 Element
*/
TypeElement parent = entry.getKey();
List<Element> childs = entry.getValue();
/**
* 每个 @Autowired 的 类 Element 的完整 name,包括 package name
* 每个 @Autowired 的 类 Element 的 package name
* 每个 @Autowired 的 类 Element 要生成的 java class name
*/
String qualifiedName = parent.getQualifiedName().toString();
String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
String fileName = parent.getSimpleName() + NAME_OF_AUTOWIRED;
logger.info(">>> Start process " + childs.size() + " field in " + parent.getSimpleName() + " ... <<<");
/**
* 生成 java class
*
* public class ???$$ARouter$$Autowired implements ISyringe
*/
TypeSpec.Builder helper = TypeSpec.classBuilder(fileName).addJavadoc(WARNING_TIPS).addSuperinterface(ClassName.get(type_ISyringe)).addModifiers(PUBLIC);
/**
* 生成 SerializationService Field
*
* private SerializationService serializationService;
*/
FieldSpec jsonServiceField = FieldSpec.builder(TypeName.get(type_JsonService.asType()), "serializationService", Modifier.PRIVATE).build();
helper.addField(jsonServiceField);
/**
* 生成 inject 方法的语句
*
* serializationService = ARouter.getInstance().navigation(SerializationService.class);;
* ???Activity substitute = (???Activity)target;
*/
injectMethodBuilder.addStatement("serializationService = $T.getInstance().navigation($T.class);", ARouterClass, ClassName.get(type_JsonService));
injectMethodBuilder.addStatement("$T substitute = ($T)target", ClassName.get(parent), ClassName.get(parent));
// Generate method body, start inject.
for (Element element : childs) {
Autowired fieldConfig = element.getAnnotation(Autowired.class);
String fieldName = element.getSimpleName().toString();
if (types.isSubtype(element.asType(), iProvider)) {
// It's provider
if ("".equals(fieldConfig.name())) {
// User has not set service path, then use byType.
// Getter
injectMethodBuilder.addStatement("substitute." + fieldName + " = $T.getInstance().navigation($T.class)", ARouterClass, ClassName.get(element.asType()));
} else {
// use byName
// Getter
injectMethodBuilder.addStatement("substitute." + fieldName + " = ($T)$T.getInstance().build($S).navigation();", ClassName.get(element.asType()), ARouterClass, fieldConfig.name());
}
// Validater
if (fieldConfig.required()) {
injectMethodBuilder.beginControlFlow("if (substitute." + fieldName + " == null)");
injectMethodBuilder.addStatement("throw new RuntimeException(\"The field '" + fieldName + "' is null, in class '\" + $T.class.getName() + \"!\")", ClassName.get(parent));
injectMethodBuilder.endControlFlow();
}
} else {
// It's normal intent value
String statment = "substitute." + fieldName + " = substitute.";
boolean isActivity = false;
if (types.isSubtype(parent.asType(), activityTm)) {
// Activity, then use getIntent()
isActivity = true;
statment += "getIntent().";
} else if (types.isSubtype(parent.asType(), fragmentTm) || types.isSubtype(parent.asType(), fragmentTmV4)) {
// Fragment, then use getArguments()
statment += "getArguments().";
} else {
throw new IllegalAccessException("The field [" + fieldName + "] need autowired from intent, its parent must be activity or fragment!");
}
statment = buildStatement(statment, typeUtils.typeExchange(element), isActivity);
if (statment.startsWith("serializationService.")) {
// Not mortals
injectMethodBuilder.beginControlFlow("if (null != serializationService)");
injectMethodBuilder.addStatement("substitute." + fieldName + " = " + statment, (StringUtils.isEmpty(fieldConfig.name()) ? fieldName : fieldConfig.name()), ClassName.get(element.asType()));
injectMethodBuilder.nextControlFlow("else");
injectMethodBuilder.addStatement("$T.e(\"" + Consts.TAG + "\", \"You want automatic inject the field '" + fieldName + "' in class '$T' , then you should implement 'SerializationService' to support object auto inject!\")", AndroidLog, ClassName.get(parent));
injectMethodBuilder.endControlFlow();
} else {
injectMethodBuilder.addStatement(statment, StringUtils.isEmpty(fieldConfig.name()) ? fieldName : fieldConfig.name());
}
// Validator
if (fieldConfig.required() && !element.asType().getKind().isPrimitive()) {
// Primitive wont be check.
injectMethodBuilder.beginControlFlow("if (null == substitute." + fieldName + ")");
injectMethodBuilder.addStatement("$T.e(\"" + Consts.TAG + "\", \"The field '" + fieldName + "' is null, in class '\" + $T.class.getName() + \"!\")", AndroidLog, ClassName.get(parent));
injectMethodBuilder.endControlFlow();
}
}
}
helper.addMethod(injectMethodBuilder.build());
/**
* 生成 Java file
*/
// Generate autowire helper
JavaFile.builder(packageName, helper.build()).build().writeTo(mFiler);
logger.info(">>> " + parent.getSimpleName() + " has been processed, " + fileName + " has been generated. <<<");
}
logger.info(">>> Autowired processor stop. <<<");
}
}
use of com.squareup.javapoet.ParameterSpec in project kripton by xcesco.
the class AbstractSelectCodeGenerator method generateMethodSignature.
/**
* Generate method signature.
*
* @param method
* the method
* @param methodBuilder
* the method builder
* @param returnTypeName
* the return type name
* @param additionalParameterSpec
* the additional parameter spec
*/
protected void generateMethodSignature(SQLiteModelMethod method, MethodSpec.Builder methodBuilder, TypeName returnTypeName, ParameterSpec... additionalParameterSpec) {
boolean finalParameter = false;
if (method.hasLiveData() && returnTypeName.equals(method.liveDataReturnClass)) {
finalParameter = true;
}
// add parameter for method
for (Pair<String, TypeName> item : method.getParameters()) {
ParameterSpec.Builder builder = ParameterSpec.builder(item.value1, item.value0);
if (finalParameter) {
builder.addModifiers(Modifier.FINAL);
}
methodBuilder.addParameter(builder.build());
}
// add additional params
for (ParameterSpec item : additionalParameterSpec) {
methodBuilder.addParameter(item);
}
// add return type
methodBuilder.returns(returnTypeName);
}
use of com.squareup.javapoet.ParameterSpec in project kripton by xcesco.
the class SqlModifyBuilder method generate.
/**
* Generate.
*
* @param classBuilder
* the class builder
* @param method
* the method
*/
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
ModifyType updateResultType = detectModifyType(method, method.jql.operationType);
// if true, field must be associate to ben attributes
TypeName returnType = method.getReturnClass();
if (updateResultType == null) {
throw (new InvalidMethodSignException(method));
}
// generate method code
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
ParameterSpec parameterSpec;
for (Pair<String, TypeName> item : method.getParameters()) {
parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
methodBuilder.addParameter(parameterSpec);
}
methodBuilder.returns(returnType);
// generate inner code
updateResultType.generate(classBuilder, methodBuilder, method, returnType);
MethodSpec methodSpec = methodBuilder.build();
classBuilder.addMethod(methodSpec);
if (method.contentProviderEntryPathEnabled) {
// delete-select, update-select can be used with content provider
// insert-select no
// if (method.jql.containsSelectOperation && updateResultType==) {
// AssertKripton.failWithInvalidMethodSignException(true, method, "
// SQL with inner SELECT can not be used in content provider");
// }
generateModifierForContentProvider(BaseProcessor.elementUtils, classBuilder, method, updateResultType);
}
}
Aggregations