use of com.squareup.javapoet.ClassName in project dagger by square.
the class InjectAdapterProcessor method generateInjectAdapter.
/**
* Write a companion class for {@code type} that extends {@link Binding}.
*
* @param constructor the injectable constructor, or null if this binding
* supports members injection only.
*/
private void generateInjectAdapter(TypeElement type, ExecutableElement constructor, List<Element> fields) throws IOException {
String packageName = getPackage(type).getQualifiedName().toString();
TypeMirror supertype = getApplicationSupertype(type);
if (supertype != null) {
supertype = processingEnv.getTypeUtils().erasure(supertype);
}
ClassName injectedClassName = ClassName.get(type);
ClassName adapterClassName = adapterName(injectedClassName, INJECT_ADAPTER_SUFFIX);
boolean isAbstract = type.getModifiers().contains(ABSTRACT);
boolean injectMembers = !fields.isEmpty() || supertype != null;
boolean disambiguateFields = !fields.isEmpty() && (constructor != null) && !constructor.getParameters().isEmpty();
boolean dependent = injectMembers || ((constructor != null) && !constructor.getParameters().isEmpty());
TypeSpec.Builder result = TypeSpec.classBuilder(adapterClassName.simpleName()).addOriginatingElement(type).addModifiers(PUBLIC, FINAL).superclass(ParameterizedTypeName.get(ClassName.get(Binding.class), injectedClassName)).addJavadoc("$L", bindingTypeDocs(injectableType(type.asType()), isAbstract, injectMembers, dependent).toString());
for (Element field : fields) {
result.addField(memberBindingField(disambiguateFields, field));
}
if (constructor != null) {
for (VariableElement parameter : constructor.getParameters()) {
result.addField(parameterBindingField(disambiguateFields, parameter));
}
}
if (supertype != null) {
result.addField(supertypeBindingField(supertype));
}
result.addMethod(writeInjectAdapterConstructor(constructor, type, injectedClassName));
if (dependent) {
result.addMethod(attachMethod(constructor, fields, disambiguateFields, injectedClassName, supertype, true));
result.addMethod(getDependenciesMethod(constructor, fields, disambiguateFields, supertype, true));
}
if (constructor != null) {
result.addMethod(getMethod(constructor, disambiguateFields, injectMembers, injectedClassName));
}
if (injectMembers) {
result.addMethod(membersInjectMethod(fields, disambiguateFields, injectedClassName, supertype));
}
JavaFile javaFile = JavaFile.builder(packageName, result.build()).addFileComment(AdapterJavadocs.GENERATED_BY_DAGGER).build();
javaFile.writeTo(processingEnv.getFiler());
}
use of com.squareup.javapoet.ClassName in project dagger by square.
the class ModuleAdapterProcessor method generateModuleAdapter.
/**
* Write a companion class for {@code type} that implements {@link
* ModuleAdapter} to expose its provider methods.
*/
private JavaFile generateModuleAdapter(TypeElement type, Map<String, Object> module, List<ExecutableElement> providerMethods) {
Object[] staticInjections = (Object[]) module.get("staticInjections");
Object[] injects = (Object[]) module.get("injects");
Object[] includes = (Object[]) module.get("includes");
boolean overrides = (Boolean) module.get("overrides");
boolean complete = (Boolean) module.get("complete");
boolean library = (Boolean) module.get("library");
List<Object> duplicateInjects = extractDuplicates(injects);
if (!duplicateInjects.isEmpty()) {
error("'injects' list contains duplicate entries: " + duplicateInjects, type);
}
List<Object> duplicateIncludes = extractDuplicates(includes);
if (!duplicateIncludes.isEmpty()) {
error("'includes' list contains duplicate entries: " + duplicateIncludes, type);
}
ClassName moduleClassName = ClassName.get(type);
ClassName adapterClassName = Util.adapterName(moduleClassName, MODULE_ADAPTER_SUFFIX);
TypeSpec.Builder adapterBuilder = TypeSpec.classBuilder(adapterClassName.simpleName()).addOriginatingElement(type).addJavadoc(AdapterJavadocs.MODULE_TYPE, Provides.class).superclass(ParameterizedTypeName.get(ClassName.get(ModuleAdapter.class), moduleClassName)).addModifiers(PUBLIC, FINAL);
adapterBuilder.addField(FieldSpec.builder(String[].class, "INJECTS").addModifiers(PRIVATE, STATIC, FINAL).initializer("$L", injectsInitializer(injects)).build());
adapterBuilder.addField(FieldSpec.builder(ARRAY_OF_CLASS, "STATIC_INJECTIONS").addModifiers(PRIVATE, STATIC, FINAL).initializer("$L", staticInjectionsInitializer(staticInjections)).build());
adapterBuilder.addField(FieldSpec.builder(ARRAY_OF_CLASS, "INCLUDES").addModifiers(PRIVATE, STATIC, FINAL).initializer("$L", includesInitializer(type, includes)).build());
adapterBuilder.addMethod(MethodSpec.constructorBuilder().addModifiers(PUBLIC).addStatement("super($T.class, INJECTS, STATIC_INJECTIONS, $L /*overrides*/, " + "INCLUDES, $L /*complete*/, $L /*library*/)", type.asType(), overrides, complete, library).build());
ExecutableElement noArgsConstructor = getNoArgsConstructor(type);
if (noArgsConstructor != null && isCallableConstructor(noArgsConstructor)) {
adapterBuilder.addMethod(MethodSpec.methodBuilder("newModule").addAnnotation(Override.class).addModifiers(PUBLIC).returns(moduleClassName).addStatement("return new $T()", type.asType()).build());
}
// Caches.
Map<ExecutableElement, ClassName> methodToClassName = new LinkedHashMap<ExecutableElement, ClassName>();
Map<String, AtomicInteger> methodNameToNextId = new LinkedHashMap<String, AtomicInteger>();
if (!providerMethods.isEmpty()) {
MethodSpec.Builder getBindings = MethodSpec.methodBuilder("getBindings").addJavadoc(AdapterJavadocs.GET_DEPENDENCIES_METHOD).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(BindingsGroup.class, "bindings").addParameter(moduleClassName, "module");
for (ExecutableElement providerMethod : providerMethods) {
Provides provides = providerMethod.getAnnotation(Provides.class);
switch(provides.type()) {
case UNIQUE:
{
getBindings.addStatement("bindings.contributeProvidesBinding($S, new $T(module))", GeneratorKeys.get(providerMethod), bindingClassName(adapterClassName, providerMethod, methodToClassName, methodNameToNextId));
break;
}
case SET:
{
getBindings.addStatement("$T.add(bindings, $S, new $T(module))", SetBinding.class, GeneratorKeys.getSetKey(providerMethod), bindingClassName(adapterClassName, providerMethod, methodToClassName, methodNameToNextId));
break;
}
case SET_VALUES:
{
getBindings.addStatement("$T.add(bindings, $S, new $T(module))", SetBinding.class, GeneratorKeys.get(providerMethod), bindingClassName(adapterClassName, providerMethod, methodToClassName, methodNameToNextId));
break;
}
default:
throw new AssertionError("Unknown @Provides type " + provides.type());
}
}
adapterBuilder.addMethod(getBindings.build());
}
for (ExecutableElement providerMethod : providerMethods) {
adapterBuilder.addType(generateProvidesAdapter(moduleClassName, adapterClassName, providerMethod, methodToClassName, methodNameToNextId, library));
}
return JavaFile.builder(adapterClassName.packageName(), adapterBuilder.build()).addFileComment(AdapterJavadocs.GENERATED_BY_DAGGER).build();
}
use of com.squareup.javapoet.ClassName in project T-MVP by north2016.
the class ApiFactoryProcessor method process.
@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) {
String CLASS_NAME = "ApiFactory";
String DATA_ARR_CLASS = "DataArr";
TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ API工厂 此类由apt自动生成");
try {
for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ApiFactory.class))) {
mAbstractProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, "正在处理: " + element.toString());
for (Element e : element.getEnclosedElements()) {
ExecutableElement executableElement = (ExecutableElement) e;
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(e.getSimpleName().toString()).addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC);
if (TypeName.get(executableElement.getReturnType()).toString().contains(DATA_ARR_CLASS)) {
// 返回列表数据
methodBuilder.returns(ClassName.get("io.reactivex", "Flowable"));
Map<String, Object> params = new HashMap<>();
methodBuilder.addParameter(params.getClass(), "param");
ClassName apiUtil = ClassName.get("com.base.util", "ApiUtil");
ClassName C = ClassName.get("com", "C");
CodeBlock.Builder blockBuilder = CodeBlock.builder();
int len = executableElement.getParameters().size();
for (int i = 0; i < len; i++) {
VariableElement ep = executableElement.getParameters().get(i);
boolean isLast = i == len - 1;
String split = (isLast ? "" : ",");
switch(ep.getSimpleName().toString()) {
case "include":
blockBuilder.add("$L.getInclude(param)" + split, apiUtil);
break;
case "where":
blockBuilder.add("$L.getWhere(param)" + split, apiUtil);
break;
case "skip":
blockBuilder.add("$L.getSkip(param)" + split, apiUtil);
break;
case "limit":
blockBuilder.add("$L.PAGE_COUNT" + split, C);
break;
case "order":
blockBuilder.add("$L._CREATED_AT" + split, C);
break;
}
}
methodBuilder.addStatement("return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())", ClassName.get("com.api", "Api"), e.getSimpleName().toString(), blockBuilder.build().toString(), ClassName.get("com.base.util.helper", "RxSchedulers"));
tb.addMethod(methodBuilder.build());
} else {
// 返回普通数据
methodBuilder.returns(TypeName.get(executableElement.getReturnType()));
String paramsString = "";
for (VariableElement ep : executableElement.getParameters()) {
methodBuilder.addParameter(TypeName.get(ep.asType()), ep.getSimpleName().toString());
paramsString += ep.getSimpleName().toString() + ",";
}
methodBuilder.addStatement("return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())", ClassName.get("com.api", "Api"), e.getSimpleName().toString(), paramsString.substring(0, paramsString.length() - 1), ClassName.get("com.base.util.helper", "RxSchedulers"));
tb.addMethod(methodBuilder.build());
}
}
}
// 生成源代码
JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();
// 在 app module/build/generated/source/apt 生成一份源代码
javaFile.writeTo(mAbstractProcessor.mFiler);
} catch (FilerException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
use of com.squareup.javapoet.ClassName in project T-MVP by north2016.
the class RouterProcessor method process.
@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) {
String CLASS_NAME = "TRouter";
TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ 全局路由器 此类由apt自动生成");
FieldSpec extraField = FieldSpec.builder(ParameterizedTypeName.get(HashMap.class, String.class, Object.class), "mCurActivityExtra").addModifiers(Modifier.PUBLIC, Modifier.STATIC).build();
tb.addField(extraField);
MethodSpec.Builder methodBuilder1 = MethodSpec.methodBuilder("go").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(String.class, "name").addParameter(HashMap.class, "extra").addParameter(ClassName.get("android.view", "View"), "view");
MethodSpec.Builder methodBuilder2 = MethodSpec.methodBuilder("bind").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(ClassName.get("android.app", "Activity"), "mContext");
List<ClassName> mList = new ArrayList<>();
CodeBlock.Builder blockBuilderGo = CodeBlock.builder();
CodeBlock.Builder blockBuilderBind = CodeBlock.builder();
ClassName appClassName = ClassName.get("com", "App");
blockBuilderGo.addStatement("mCurActivityExtra=extra");
blockBuilderGo.addStatement("Activity mContext=$T.getAppContext().getCurActivity()", appClassName);
// 括号开始
blockBuilderGo.beginControlFlow(" switch (name)");
blockBuilderBind.addStatement("if(mCurActivityExtra==null) return");
// 括号开始
blockBuilderBind.beginControlFlow(" switch (mContext.getClass().getSimpleName())");
List<RouterActivityModel> mRouterActivityModels = new ArrayList<>();
try {
for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(Router.class))) {
ClassName currentType = ClassName.get(element);
if (mList.contains(currentType))
continue;
mList.add(currentType);
RouterActivityModel mRouterActivityModel = new RouterActivityModel();
mRouterActivityModel.setElement(element);
mRouterActivityModel.setActionName(element.getAnnotation(Router.class).value());
List<Element> mExtraElements = new ArrayList<>();
List<String> mExtraElementKeys = new ArrayList<>();
for (Element childElement : element.getEnclosedElements()) {
SceneTransition mSceneTransitionAnnotation = childElement.getAnnotation(SceneTransition.class);
if (mSceneTransitionAnnotation != null) {
mRouterActivityModel.setSceneTransitionElementName(mSceneTransitionAnnotation.value());
mRouterActivityModel.setSceneTransitionElement(childElement);
}
Extra mExtraAnnotation = childElement.getAnnotation(Extra.class);
if (mExtraAnnotation != null) {
mExtraElementKeys.add(mExtraAnnotation.value());
mExtraElements.add(childElement);
}
}
mRouterActivityModel.setExtraElementKeys(mExtraElementKeys);
mRouterActivityModel.setExtraElements(mExtraElements);
boolean isNeedBind = (mExtraElementKeys != null && mExtraElementKeys.size() > 0 || mRouterActivityModel.getSceneTransitionElement() != null);
mRouterActivityModel.setNeedBind(isNeedBind);
mRouterActivityModels.add(mRouterActivityModel);
}
ClassName mActivityCompatName = ClassName.get("android.support.v4.app", "ActivityCompat");
ClassName mIntentClassName = ClassName.get("android.content", "Intent");
ClassName mActivityOptionsCompatName = ClassName.get("android.support.v4.app", "ActivityOptionsCompat");
for (RouterActivityModel item : mRouterActivityModels) {
// 1
blockBuilderGo.add("case $S: \n", item.getActionName());
if (item.isNeedBind())
// 1
blockBuilderBind.add("case $S: \n", item.getElement().getSimpleName());
if (item.getExtraElements() != null && item.getExtraElements().size() > 0) {
for (int i = 0; i < item.getExtraElements().size(); i++) {
Element mFiled = item.getExtraElements().get(i);
blockBuilderBind.add(// 1
"(($T)mContext)." + // 2
"$L" + // 3
"= ($T) " + // 4
"mCurActivityExtra.get(" + // 5
"$S);\n", // 1
item.getElement(), // 2
mFiled, // 3
mFiled, // 5
item.getExtraElementKeys().get(i));
// 5
}
}
if (item.getSceneTransitionElement() != null) {
blockBuilderGo.add(// 2
"$L.startActivity(mContext," + // 3
"\nnew $L(mContext," + // 4
"\n$L.class)," + // 5
"\n$T.makeSceneTransitionAnimation(" + // 6
"\nmContext,view," + // 7
"\n$S).toBundle());", // 2
mActivityCompatName, // 3
mIntentClassName, // 4
item.getElement(), // 5
mActivityOptionsCompatName, // 6
item.getSceneTransitionElementName());
blockBuilderBind.add(// 2
"$T.setTransitionName(" + // 3
"(($T)mContext).mViewBinding." + // 4
"$L, " + // 5
"$S);\n", // 2
ClassName.get("android.support.v4.view", "ViewCompat"), // 3
item.getElement(), // 4
item.getSceneTransitionElement(), // 5
item.getSceneTransitionElementName());
} else {
blockBuilderGo.add(// 2
"mContext.startActivity(" + // 3
"\nnew $L(mContext," + // 7
"\n$L.class));", // 3
mIntentClassName, // 4
item.getElement());
}
// 1
blockBuilderGo.addStatement("\nbreak");
// 1
if (item.isNeedBind())
blockBuilderBind.addStatement("break");
}
blockBuilderGo.addStatement("default: break");
blockBuilderGo.endControlFlow();
methodBuilder1.addCode(blockBuilderGo.build());
blockBuilderBind.addStatement("default: break");
blockBuilderBind.endControlFlow();
methodBuilder2.addCode(blockBuilderBind.build());
tb.addMethod(methodBuilder1.build());
tb.addMethod(methodBuilder2.build());
// 增加go(action)和go(action,extra):两个重载方法
tb.addMethod(MethodSpec.methodBuilder("go").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(String.class, "name").addParameter(HashMap.class, "extra").addCode("go(name,extra,null);\n").build());
tb.addMethod(MethodSpec.methodBuilder("go").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(String.class, "name").addCode("go(name,null,null);\n").build());
// 生成源代码
JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();
// 在 app module/build/generated/source/apt 生成一份源代码
javaFile.writeTo(mAbstractProcessor.mFiler);
} catch (FilerException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
use of com.squareup.javapoet.ClassName in project T-MVP by north2016.
the class InstanceProcessor method process.
@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) {
String CLASS_NAME = "InstanceFactory";
TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ 实例化工厂 此类由apt自动生成");
MethodSpec.Builder methodBuilder1 = MethodSpec.methodBuilder("create").addAnnotation(MemoryCache.class).addJavadoc("@此方法由apt自动生成").returns(Object.class).addModifiers(PUBLIC, STATIC).addException(IllegalAccessException.class).addException(InstantiationException.class).addParameter(Class.class, "mClass");
List<ClassName> mList = new ArrayList<>();
CodeBlock.Builder blockBuilder = CodeBlock.builder();
// 括号开始
blockBuilder.beginControlFlow(" switch (mClass.getSimpleName())");
try {
for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(InstanceFactory.class))) {
mAbstractProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, "正在处理: " + element.toString());
if (!Utils.isValidClass(mAbstractProcessor.mMessager, element))
return;
ClassName currentType = ClassName.get(element);
if (mList.contains(currentType))
continue;
mList.add(currentType);
// String className = null;
// try {
// Class<?> clazz = element.getAnnotation(InstanceFactory.class).value();
// className = clazz.getCanonicalName();
// } catch (MirroredTypeException mte) {
// DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();
// TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
// className = classTypeElement.getQualifiedName().toString();
// } catch (Exception e) {
// }
// if (className != null && !className.equals(InstanceFactory.class.getName())) {
// blockBuilder.addStatement("case $S: return new $T()", currentType.simpleName(), Utils.getType(className));//初始化Repository
// } else {
// 初始化Presenter
blockBuilder.addStatement("case $S: return new $T()", currentType.simpleName(), currentType);
// }
}
blockBuilder.addStatement("default: return mClass.newInstance()");
blockBuilder.endControlFlow();
methodBuilder1.addCode(blockBuilder.build());
tb.addMethod(methodBuilder1.build());
// 生成源代码
JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();
// 在 app module/build/generated/source/apt 生成一份源代码
javaFile.writeTo(mAbstractProcessor.mFiler);
} catch (FilerException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Aggregations