use of com.squareup.javapoet.ClassName in project DeepLinkDispatch by airbnb.
the class DeepLinkProcessor method generateDeepLinkDelegate.
private void generateDeepLinkDelegate(String packageName, List<TypeElement> loaderClasses) throws IOException {
MethodSpec notifyListenerMethod = MethodSpec.methodBuilder("notifyListener").addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(void.class).addParameter(ANDROID_CONTEXT, "context").addParameter(boolean.class, "isError").addParameter(ClassName.get("android.net", "Uri"), "uri").addParameter(String.class, "errorMessage").addStatement("$T intent = new Intent()", ANDROID_INTENT).addStatement("intent.setAction($T.ACTION)", DeepLinkHandler.class).addStatement("intent.putExtra($T.EXTRA_URI, uri != null ? uri.toString() : $S)", DeepLinkHandler.class, "").addStatement("intent.putExtra($T.EXTRA_SUCCESSFUL, !isError)", DeepLinkHandler.class).beginControlFlow("if (isError)").addStatement("intent.putExtra($T.EXTRA_ERROR_MESSAGE, errorMessage)", DeepLinkHandler.class).endControlFlow().addStatement("$T.getInstance(context).sendBroadcast(intent)", ClassName.get("android.support.v4.content", "LocalBroadcastManager")).build();
ClassName deepLinkResult = ClassName.get(DLD_PACKAGE_NAME, "DeepLinkResult");
MethodSpec createResultAndNotifyMethod = MethodSpec.methodBuilder("createResultAndNotify").addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(deepLinkResult).addParameter(ANDROID_CONTEXT, "context").addParameter(TypeName.BOOLEAN, "successful", Modifier.FINAL).addParameter(ANDROID_URI, "uri", Modifier.FINAL).addParameter(ClassName.get(String.class), "error", Modifier.FINAL).addStatement("notifyListener(context, !successful, uri, error)").addStatement("return new $T(successful, uri != null ? uri.toString() : null, error)", deepLinkResult).build();
FieldSpec tag = FieldSpec.builder(String.class, "TAG", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("DeepLinkDelegate.class.getSimpleName()").build();
FieldSpec loaders = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class), WildcardTypeName.subtypeOf(Parser.class)), "loaders", Modifier.PRIVATE, Modifier.FINAL).build();
CodeBlock.Builder loadersInitializer = CodeBlock.builder().add("this.loaders = $T.asList(\n", ClassName.get(Arrays.class)).indent();
int totalElements = loaderClasses.size();
for (int i = 0; i < totalElements; i++) {
loadersInitializer.add("$L$L", decapitalize(moduleNameToLoaderName(loaderClasses.get(i))), i < totalElements - 1 ? "," : "");
}
MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameters(FluentIterable.from(loaderClasses).transform(new Function<TypeElement, ParameterSpec>() {
@Override
public ParameterSpec apply(TypeElement typeElement) {
return ParameterSpec.builder(moduleElementToLoaderClassName(typeElement), decapitalize(moduleNameToLoaderName(typeElement))).build();
}
}).toList()).addCode(loadersInitializer.unindent().add(");\n").build()).build();
MethodSpec supportsUri = MethodSpec.methodBuilder("supportsUri").addModifiers(Modifier.PUBLIC).returns(TypeName.BOOLEAN).addParameter(String.class, "uriString").addStatement("return findEntry(uriString) != null").build();
MethodSpec findEntry = MethodSpec.methodBuilder("findEntry").addModifiers(Modifier.PRIVATE).returns(CLASS_DLD_ENTRY).addParameter(String.class, "uriString").beginControlFlow("for (Parser loader : loaders)").addStatement("$T entry = loader.parseUri(uriString)", CLASS_DLD_ENTRY).beginControlFlow("if (entry != null)").addStatement("return entry").endControlFlow().endControlFlow().addStatement("return null").build();
MethodSpec dispatchFromMethod = MethodSpec.methodBuilder("dispatchFrom").addModifiers(Modifier.PUBLIC).returns(deepLinkResult).addParameter(ANDROID_ACTIVITY, "activity").beginControlFlow("if (activity == null)").addStatement("throw new $T($S)", NullPointerException.class, "activity == null").endControlFlow().addStatement("return dispatchFrom(activity, activity.getIntent())").build();
MethodSpec dispatchFromMethodWithIntent = MethodSpec.methodBuilder("dispatchFrom").addModifiers(Modifier.PUBLIC).returns(deepLinkResult).addParameter(ANDROID_ACTIVITY, "activity").addParameter(ANDROID_INTENT, "sourceIntent").beginControlFlow("if (activity == null)").addStatement("throw new $T($S)", NullPointerException.class, "activity == null").endControlFlow().beginControlFlow("if (sourceIntent == null)").addStatement("throw new $T($S)", NullPointerException.class, "sourceIntent == null").endControlFlow().addStatement("$T uri = sourceIntent.getData()", ANDROID_URI).beginControlFlow("if (uri == null)").addStatement("return createResultAndNotify(activity, false, null, $S)", "No Uri in given activity's intent.").endControlFlow().addStatement("String uriString = uri.toString()").addStatement("$T entry = findEntry(uriString)", CLASS_DLD_ENTRY).beginControlFlow("if (entry != null)").addStatement("$T deepLinkUri = DeepLinkUri.parse(uriString)", CLASS_DLD_URI).addStatement("$T<String, String> parameterMap = entry.getParameters(uriString)", Map.class).beginControlFlow("for (String queryParameter : deepLinkUri.queryParameterNames())").beginControlFlow("for (String queryParameterValue : deepLinkUri.queryParameterValues(queryParameter))").beginControlFlow("if (parameterMap.containsKey(queryParameter))").addStatement("$T.w(TAG, \"Duplicate parameter name in path and query param: \" + queryParameter)", ClassName.get("android.util", "Log")).endControlFlow().addStatement("parameterMap.put(queryParameter, queryParameterValue)").endControlFlow().endControlFlow().addStatement("parameterMap.put($T.URI, uri.toString())", ClassName.get(DLD_PACKAGE_NAME, "DeepLink")).addStatement("$T parameters", ANDROID_BUNDLE).beginControlFlow("if (sourceIntent.getExtras() != null)").addStatement("parameters = new Bundle(sourceIntent.getExtras())").nextControlFlow("else").addStatement("parameters = new Bundle()").endControlFlow().beginControlFlow("for (Map.Entry<String, String> parameterEntry : parameterMap.entrySet())").addStatement("parameters.putString(parameterEntry.getKey(), parameterEntry.getValue())").endControlFlow().beginControlFlow("try").addStatement("Class<?> c = entry.getActivityClass()").addStatement("$T newIntent", ANDROID_INTENT).addStatement("$T taskStackBuilder = null", TASK_STACK_BUILDER).beginControlFlow("if (entry.getType() == DeepLinkEntry.Type.CLASS)").addStatement("newIntent = new Intent(activity, c)").nextControlFlow("else").addStatement("$T method", Method.class).beginControlFlow("try").addStatement("method = c.getMethod(entry.getMethod(), $T.class)", ANDROID_CONTEXT).beginControlFlow("if (method.getReturnType().equals($T.class))", TASK_STACK_BUILDER).addStatement("taskStackBuilder = (TaskStackBuilder) method.invoke(c, activity)").beginControlFlow("if (taskStackBuilder.getIntentCount() == 0)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod() + \" intents length == 0\" )").endControlFlow().addStatement("newIntent = taskStackBuilder." + "editIntentAt(taskStackBuilder.getIntentCount()-1)").nextControlFlow("else").addStatement("newIntent = (Intent) method.invoke(c, activity)").endControlFlow().nextControlFlow("catch ($T exception)", NoSuchMethodException.class).addStatement("method = c.getMethod(entry.getMethod(), $T.class, $T.class)", ANDROID_CONTEXT, ANDROID_BUNDLE).beginControlFlow("if (method.getReturnType().equals($T.class))", TASK_STACK_BUILDER).addStatement("taskStackBuilder = " + "(TaskStackBuilder) method.invoke(c, activity, parameters)").beginControlFlow("if (taskStackBuilder.getIntentCount() == 0)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod() + \" intents length == 0\" )").endControlFlow().addStatement("newIntent = taskStackBuilder." + "editIntentAt(taskStackBuilder.getIntentCount()-1)").nextControlFlow("else").addStatement("newIntent = (Intent) method.invoke(c, activity, parameters)").endControlFlow().endControlFlow().endControlFlow().beginControlFlow("if (newIntent.getAction() == null)").addStatement("newIntent.setAction(sourceIntent.getAction())").endControlFlow().beginControlFlow("if (newIntent.getData() == null)").addStatement("newIntent.setData(sourceIntent.getData())").endControlFlow().addStatement("newIntent.putExtras(parameters)").addStatement("newIntent.putExtra(DeepLink.IS_DEEP_LINK, true)").addStatement("newIntent.putExtra(DeepLink.REFERRER_URI, uri)").beginControlFlow("if (activity.getCallingActivity() != null)").addStatement("newIntent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT)").endControlFlow().beginControlFlow("if (taskStackBuilder != null)").addStatement("taskStackBuilder.startActivities()").nextControlFlow("else").addStatement("activity.startActivity(newIntent)").endControlFlow().addStatement("return createResultAndNotify(activity, true, uri, null)").nextControlFlow("catch (NoSuchMethodException exception)").addStatement("return createResultAndNotify(activity, false, uri, \"Deep link to " + "non-existent method: \" + entry.getMethod())").nextControlFlow("catch (IllegalAccessException exception)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())").nextControlFlow("catch ($T exception)", InvocationTargetException.class).addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())").endControlFlow().nextControlFlow("else").addStatement("return createResultAndNotify(activity, false, uri, " + "\"No registered entity to handle deep link: \" + uri.toString())").endControlFlow().build();
TypeSpec deepLinkDelegate = TypeSpec.classBuilder("DeepLinkDelegate").addModifiers(Modifier.PUBLIC, Modifier.FINAL).addField(tag).addField(loaders).addMethod(constructor).addMethod(findEntry).addMethod(dispatchFromMethod).addMethod(dispatchFromMethodWithIntent).addMethod(createResultAndNotifyMethod).addMethod(notifyListenerMethod).addMethod(supportsUri).build();
JavaFile.builder(packageName, deepLinkDelegate).build().writeTo(filer);
}
use of com.squareup.javapoet.ClassName in project ARouter by alibaba.
the class RouteProcessor method parseRoutes.
private void parseRoutes(Set<? extends Element> routeElements) throws IOException {
if (CollectionUtils.isNotEmpty(routeElements)) {
// Perpare the type an so on.
logger.info(">>> Found routes, size is " + routeElements.size() + " <<<");
rootMap.clear();
TypeMirror type_Activity = elements.getTypeElement(ACTIVITY).asType();
TypeMirror type_Service = elements.getTypeElement(SERVICE).asType();
TypeElement type_Parcelable = elements.getTypeElement(PARCELABLE);
// Interface of ARouter
TypeElement type_IRouteGroup = elements.getTypeElement(IROUTE_GROUP);
TypeElement type_IProviderGroup = elements.getTypeElement(IPROVIDER_GROUP);
ClassName routeMetaCn = ClassName.get(RouteMeta.class);
ClassName routeTypeCn = ClassName.get(RouteType.class);
/*
Build input type, format as :
```Map<String, Class<? extends IRouteGroup>>```
*/
ParameterizedTypeName inputMapTypeOfRoot = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(type_IRouteGroup))));
/*
```Map<String, RouteMeta>```
*/
ParameterizedTypeName inputMapTypeOfGroup = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ClassName.get(RouteMeta.class));
/*
Build input param name.
*/
ParameterSpec rootParamSpec = ParameterSpec.builder(inputMapTypeOfRoot, "routes").build();
ParameterSpec groupParamSpec = ParameterSpec.builder(inputMapTypeOfGroup, "atlas").build();
// Ps. its param type same as groupParamSpec!
ParameterSpec providerParamSpec = ParameterSpec.builder(inputMapTypeOfGroup, "providers").build();
/*
Build method : 'loadInto'
*/
MethodSpec.Builder loadIntoMethodOfRootBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(rootParamSpec);
// Follow a sequence, find out metas of group first, generate java file, then statistics them as root.
for (Element element : routeElements) {
TypeMirror tm = element.asType();
Route route = element.getAnnotation(Route.class);
RouteMeta routeMete = null;
if (types.isSubtype(tm, type_Activity)) {
// Activity
logger.info(">>> Found activity route: " + tm.toString() + " <<<");
// Get all fields annotation by @Autowired
Map<String, Integer> paramsType = new HashMap<>();
for (Element field : element.getEnclosedElements()) {
if (field.getKind().isField() && field.getAnnotation(Autowired.class) != null && !types.isSubtype(field.asType(), iProvider)) {
// It must be field, then it has annotation, but it not be provider.
Autowired paramConfig = field.getAnnotation(Autowired.class);
paramsType.put(StringUtils.isEmpty(paramConfig.name()) ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeExchange(field));
}
}
routeMete = new RouteMeta(route, element, RouteType.ACTIVITY, paramsType);
} else if (types.isSubtype(tm, iProvider)) {
// IProvider
logger.info(">>> Found provider route: " + tm.toString() + " <<<");
routeMete = new RouteMeta(route, element, RouteType.PROVIDER, null);
} else if (types.isSubtype(tm, type_Service)) {
// Service
logger.info(">>> Found service route: " + tm.toString() + " <<<");
routeMete = new RouteMeta(route, element, RouteType.parse(SERVICE), null);
}
categories(routeMete);
// if (StringUtils.isEmpty(moduleName)) { // Hasn't generate the module name.
// moduleName = ModuleUtils.generateModuleName(element, logger);
// }
}
MethodSpec.Builder loadIntoMethodOfProviderBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(providerParamSpec);
// Start generate java source, structure is divided into upper and lower levels, used for demand initialization.
for (Map.Entry<String, Set<RouteMeta>> entry : groupMap.entrySet()) {
String groupName = entry.getKey();
MethodSpec.Builder loadIntoMethodOfGroupBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(groupParamSpec);
// Build group method body
Set<RouteMeta> groupData = entry.getValue();
for (RouteMeta routeMeta : groupData) {
switch(routeMeta.getType()) {
case // Need cache provider's super class
PROVIDER:
List<? extends TypeMirror> interfaces = ((TypeElement) routeMeta.getRawType()).getInterfaces();
for (TypeMirror tm : interfaces) {
if (types.isSubtype(tm, iProvider)) {
// This interface extend the IProvider, so it can be used for mark provider
loadIntoMethodOfProviderBuilder.addStatement("providers.put($S, $T.build($T." + routeMeta.getType() + ", $T.class, $S, $S, null, " + routeMeta.getPriority() + ", " + routeMeta.getExtra() + "))", // Spite unuseless name
tm.toString().substring(tm.toString().lastIndexOf(".") + 1), routeMetaCn, routeTypeCn, ClassName.get((TypeElement) routeMeta.getRawType()), routeMeta.getPath(), routeMeta.getGroup());
}
}
break;
default:
break;
}
// Make map body for paramsType
StringBuilder mapBodyBuilder = new StringBuilder();
Map<String, Integer> paramsType = routeMeta.getParamsType();
if (MapUtils.isNotEmpty(paramsType)) {
for (Map.Entry<String, Integer> types : paramsType.entrySet()) {
mapBodyBuilder.append("put(\"").append(types.getKey()).append("\", ").append(types.getValue()).append("); ");
}
}
String mapBody = mapBodyBuilder.toString();
loadIntoMethodOfGroupBuilder.addStatement("atlas.put($S, $T.build($T." + routeMeta.getType() + ", $T.class, $S, $S, " + (StringUtils.isEmpty(mapBody) ? null : ("new java.util.HashMap<String, Integer>(){{" + mapBodyBuilder.toString() + "}}")) + ", " + routeMeta.getPriority() + ", " + routeMeta.getExtra() + "))", routeMeta.getPath(), routeMetaCn, routeTypeCn, ClassName.get((TypeElement) routeMeta.getRawType()), routeMeta.getPath().toLowerCase(), routeMeta.getGroup().toLowerCase());
}
// Generate groups
String groupFileName = NAME_OF_GROUP + groupName;
JavaFile.builder(PACKAGE_OF_GENERATE_FILE, TypeSpec.classBuilder(groupFileName).addJavadoc(WARNING_TIPS).addSuperinterface(ClassName.get(type_IRouteGroup)).addModifiers(PUBLIC).addMethod(loadIntoMethodOfGroupBuilder.build()).build()).build().writeTo(mFiler);
logger.info(">>> Generated group: " + groupName + "<<<");
rootMap.put(groupName, groupFileName);
}
if (MapUtils.isNotEmpty(rootMap)) {
// Generate root meta by group name, it must be generated before root, then I can findout the class of group.
for (Map.Entry<String, String> entry : rootMap.entrySet()) {
loadIntoMethodOfRootBuilder.addStatement("routes.put($S, $T.class)", entry.getKey(), ClassName.get(PACKAGE_OF_GENERATE_FILE, entry.getValue()));
}
}
// Wirte provider into disk
String providerMapFileName = NAME_OF_PROVIDER + SEPARATOR + moduleName;
JavaFile.builder(PACKAGE_OF_GENERATE_FILE, TypeSpec.classBuilder(providerMapFileName).addJavadoc(WARNING_TIPS).addSuperinterface(ClassName.get(type_IProviderGroup)).addModifiers(PUBLIC).addMethod(loadIntoMethodOfProviderBuilder.build()).build()).build().writeTo(mFiler);
logger.info(">>> Generated provider map, name is " + providerMapFileName + " <<<");
// Write root meta into disk.
String rootFileName = NAME_OF_ROOT + SEPARATOR + moduleName;
JavaFile.builder(PACKAGE_OF_GENERATE_FILE, TypeSpec.classBuilder(rootFileName).addJavadoc(WARNING_TIPS).addSuperinterface(ClassName.get(elements.getTypeElement(ITROUTE_ROOT))).addModifiers(PUBLIC).addMethod(loadIntoMethodOfRootBuilder.build()).build()).build().writeTo(mFiler);
logger.info(">>> Generated root, name is " + rootFileName + " <<<");
}
}
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("rx", "Observable"));
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 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();
}
}
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自动生成");
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("$T.getAppContext().mCurActivityExtra=extra", appClassName);
blockBuilderGo.addStatement("Activity mContext=$T.getAppContext().getCurActivity()", appClassName);
//括号开始
blockBuilderGo.beginControlFlow(" switch (name)");
//括号开始
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
"$T.getAppContext().mCurActivityExtra.get(" + //5
"$S);\n", //1
item.getElement(), //2
mFiled, //3
mFiled, //4
appClassName, //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)." + //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();
}
}
Aggregations