Java Code Examples for com.squareup.javapoet.ClassName#simpleName()

The following examples show how to use com.squareup.javapoet.ClassName#simpleName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeUtils.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
public static String reflectionName(ClassName className) {
        // trivial case: no nested names
//        if (className.names.size() == 2) {
//            String packageName = packageName();
//            if (packageName.isEmpty()) {
//                return className.simpleName();
//            }
//            return packageName + "." + className.simpleName();
//        }
//        // concat top level class name and nested names
//        StringBuilder builder = new StringBuilder();
//        builder.append(className.topLevelClassName());
//        for (String name : className.simpleNames().subList(1, className.simpleNames().size())) {
//            builder.append('$').append(name);
//        }
        return className.packageName() + "." + className.simpleName();
    }
 
Example 2
Source File: TypeUtils.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
public static String reflectionName(ClassName className) {
        // trivial case: no nested names
//        if (className.names.size() == 2) {
//            String packageName = packageName();
//            if (packageName.isEmpty()) {
//                return className.simpleName();
//            }
//            return packageName + "." + className.simpleName();
//        }
//        // concat top level class name and nested names
//        StringBuilder builder = new StringBuilder();
//        builder.append(className.topLevelClassName());
//        for (String name : className.simpleNames().subList(1, className.simpleNames().size())) {
//            builder.append('$').append(name);
//        }
        return className.packageName() + "." + className.simpleName();
    }
 
Example 3
Source File: BundleExtension.java    From auto-value-bundle with MIT License 6 votes vote down vote up
private MethodSpec generateUnboxMethod(
        ClassName className,
        TypeName typeName,
        String primitiveType) {
    String paramName = className.simpleName() + "Param";
    paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1);
    String primitiveArray = primitiveType + "s";
    return MethodSpec.methodBuilder("toPrimitive")
            .addParameters(ImmutableList.of(ParameterSpec.builder(ArrayTypeName.of(className), paramName).build()))
            .returns(ArrayTypeName.of(typeName))
            .addModifiers(PUBLIC)
            .addModifiers(STATIC)
            .addStatement("$L[] $L = new $L[$L.length]", primitiveType, primitiveArray, primitiveType, paramName)
            .beginControlFlow("for (int i = 0; i < $L.length; i++)", paramName)
            .addStatement("$L[i] = $L[i]", primitiveArray, paramName)
            .endControlFlow()
            .addStatement("return $L", primitiveArray)
            .build();
}
 
Example 4
Source File: RxObserveProcessor.java    From Rx.Observe with Apache License 2.0 5 votes vote down vote up
private void writeRxObserve() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.CLASS)
            .addModifiers(Modifier.PUBLIC);

    for (ClassName className : observeHolders.keySet()) {
        final ObserveHolder observeHolder = observeHolders.get(className);
        final String simpleName = className.simpleName();
        final TypeName returnType = ClassName.bestGuess(className.packageName() + "." + simpleName + Constants.OBSERVE_CLASS);

        if (processUtils.allMethodsAreStatic(observeHolder.methods)) {
            builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_OF + simpleName)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(returnType)
                    .addStatement("return new $T()", returnType)
                    .build());
        } else {
            builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_OF)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(className, Constants.TARGET)
                    .returns(returnType)
                    .addStatement("return new $T($L)", returnType, Constants.TARGET)
                    .build());
        }
    }

    final TypeSpec newClass = builder.build();

    final JavaFile javaFile = JavaFile.builder(Constants.PACKAGE, newClass).build();

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: ComponentProcessing.java    From Auto-Dagger2 with MIT License 5 votes vote down vote up
private List<MethodSpec> getSubcomponents() {
    if (extractor.getSubcomponentsTypeMirrors().isEmpty()) {
        return Collections.emptyList();
    }

    List<MethodSpec> methodSpecs = new ArrayList<>(extractor.getSubcomponentsTypeMirrors().size());
    for (TypeMirror typeMirror : extractor.getSubcomponentsTypeMirrors()) {
        Element e = MoreTypes.asElement(typeMirror);
        TypeName typeName;
        String name;
        if (MoreElements.isAnnotationPresent(e, AutoSubcomponent.class)) {
            ClassName cls = AutoComponentClassNameUtil.getComponentClassName(e);
            typeName = cls;
            name = cls.simpleName();
        } else {
            typeName = TypeName.get(typeMirror);
            name = e.getSimpleName().toString();
        }

        List<TypeMirror> modules = state.getSubcomponentModules(typeMirror);
        List<ParameterSpec> parameterSpecs;
        if(modules != null) {
            parameterSpecs = new ArrayList<>(modules.size());
            int count = 0;
            for (TypeMirror moduleTypeMirror : modules) {
                parameterSpecs.add(ParameterSpec.builder(TypeName.get(moduleTypeMirror), String.format("module%d", ++count)).build());
            }
        } else {
            parameterSpecs = new ArrayList<>(0);
        }

        methodSpecs.add(MethodSpec.methodBuilder("plus" + name)
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .addParameters(parameterSpecs)
                .returns(typeName)
                .build());
    }

    return methodSpecs;
}
 
Example 6
Source File: ProcessUtils.java    From Freezer with Apache License 2.0 5 votes vote down vote up
public static String getFieldClassName(Element element) {
    String name;

    TypeName t = getFieldClass(element);
    if (t instanceof ClassName) {
        ClassName className = (ClassName) t;
        name = className.simpleName();
    } else {
        name = t.toString();
    }

    return name;
}
 
Example 7
Source File: ActivityProcessor.java    From grouter-android with Apache License 2.0 5 votes vote down vote up
public List<ActivityModel> process(RoundEnvironment roundEnv) {
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(RouterActivity.class);
    List<ActivityModel> typeModels = new ArrayList<>();
    for (Element element : elements) {
        TypeElement typeElement = (TypeElement) element;
        RouterActivity routerActivity = typeElement.getAnnotation(RouterActivity.class);
        ActivityModel typeModel = new ActivityModel();
        typeModels.add(typeModel);
        typeModel.exported = routerActivity.exported();
        typeModel.name = routerActivity.name();
        typeModel.description = routerActivity.description();
        typeModel.path = routerActivity.value();

        // 设置类名
        ClassName className = (ClassName) ClassName.get(typeElement.asType());
        typeModel.type = className.packageName() + "." + className.simpleName();
        // 设置参数
        List<? extends Element> members = routerProcessor.elementUtils.getAllMembers(typeElement);
        for (Element mb : members) {
            RouterField routerField = mb.getAnnotation(RouterField.class);
            if (routerField == null) {
                continue;
            }
            if (!mb.getEnclosingElement().equals(typeElement)) {
                System.out.println("父类属性");
                continue;
            }
            ParameterModel parameterModel = new ParameterModel();
            parameterModel.queryName = routerField.value();
            TypeName typeName = TypeName.get(mb.asType());
            parameterModel.rawType = typeName.toString();
            parameterModel.type = TypeUtils.getRouterActivityTypeString(typeName);
            parameterModel.name = mb.getSimpleName().toString();
            typeModel.params.add(parameterModel);
        }

    }
    Collections.sort(typeModels);
    return typeModels;
}
 
Example 8
Source File: AnnotationBuilder.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static String compositeName(ClassName annotation) {
  ClassName parentName = annotation.enclosingClassName();
  if (parentName == null) {
    return "At" + annotation.simpleName();
  }
  return compositeName(parentName) + annotation.simpleName();
}
 
Example 9
Source File: ProcessUtils.java    From RxAndroidOrm with Apache License 2.0 5 votes vote down vote up
public static String getFieldClassName(Element element) {
    String name;

    TypeName t = getFieldClass(element);
    if (t instanceof ClassName) {
        ClassName className = (ClassName) t;
        name = className.simpleName();
    } else {
        name = t.toString();
    }

    return name;
}
 
Example 10
Source File: OutputSpecFactory.java    From dataenum with Apache License 2.0 5 votes vote down vote up
static ClassName toOutputClassName(ClassName specClassName) throws ParserException {
  String packageName = specClassName.packageName();
  String name = specClassName.simpleName();

  if (!isSpecClassName(specClassName)) {
    throw new ParserException(
        String.format(
            "Bad name for DataEnum interface! Name must end with '%s', found: %s", SUFFIX, name));
  }

  String nameWithoutSuffix = name.substring(0, name.length() - SUFFIX.length());
  return ClassName.get(packageName, nameWithoutSuffix);
}
 
Example 11
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 5 votes vote down vote up
public static ClassName toInitializerNameFromConfigurationName(ClassName type) {
	String name = type.simpleName();
	if (type.enclosingClassName() != null) {
		name = type.enclosingClassName().simpleName() + "_" + name;
	}
	return ClassName.get(type.packageName(), name + "Initializer");
}
 
Example 12
Source File: ElementUtils.java    From OkDeepLink with Apache License 2.0 4 votes vote down vote up
public static String getName(ClassName className) {
    return className.packageName()+"."+ className.simpleName();
}
 
Example 13
Source File: Bundlables.java    From auto-value-bundle with MIT License 4 votes vote down vote up
private static String getMethodName(ClassName className) {
    return "get" + className.simpleName();
}
 
Example 14
Source File: DaggerAutoInjectProcessor.java    From DaggerAutoInject with Apache License 2.0 4 votes vote down vote up
private ClassName findComponent(TypeMirror typeMirror) {
    final ClassName typeName = (ClassName) TypeName.get(typeMirror);
    final String packageName = typeName.packageName();
    final String className = typeName.simpleName();
    return ClassName.bestGuess(packageName + "." + className);
}
 
Example 15
Source File: DaggerAutoInjectProcessor.java    From DaggerAutoInject with Apache License 2.0 4 votes vote down vote up
private ClassName findDaggerComponent(TypeMirror typeMirror) {
    final ClassName typeName = (ClassName) TypeName.get(typeMirror);
    final String packageName = typeName.packageName();
    final String className = typeName.simpleName();
    return ClassName.bestGuess(packageName + "." + Constants.DAGGER + className);
}
 
Example 16
Source File: TaskProcessor.java    From grouter-android with Apache License 2.0 4 votes vote down vote up
public List<TaskModel> process(RoundEnvironment roundEnv) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(RouterTask.class);
        List<TaskModel> typeModels = new ArrayList<>();
        for (Element element : elements) {
            TypeElement typeElement = (TypeElement) element;
            TaskModel typeModel = new TaskModel();
            RouterTask routerTask = element.getAnnotation(RouterTask.class);
            typeModel.returns = routerTask.returns();
            typeModel.name = routerTask.name();
            typeModel.description = routerTask.description();
            // 设置类名
            ClassName className = (ClassName) ClassName.get(typeElement.asType());
            typeModel.type = className.packageName() + "." + className.simpleName();
            // 设置参数
            List<? extends Element> members = routerProcessor.elementUtils.getAllMembers(typeElement);
            for (Element mb : members) {
                RouterField routerField = mb.getAnnotation(RouterField.class);
                if (routerField == null) {
                    continue;
                }
                if (!mb.getEnclosingElement().equals(typeElement)) {
                    System.out.println("父类属性");
                    continue;
                }
//                    System.out.println("getEnclosingElement:"+mb.getEnclosingElement().getSimpleName());
                ParameterModel parameterModel = new ParameterModel();
                parameterModel.queryName = routerField.value();
                TypeName typeName = TypeName.get(mb.asType());
                parameterModel.rawType = typeName.toString();
                parameterModel.type = TypeUtils.getRouterTaskTypeString(typeName);
                parameterModel.name = mb.getSimpleName().toString();
                typeModel.params.add(parameterModel);
            }
            // 设置路径
            RouterTask routerActivity = typeElement.getAnnotation(RouterTask.class);
            typeModel.path = routerActivity.value();
            typeModels.add(typeModel);
        }
        Collections.sort(typeModels);
//        String json = JSON.toJSONString(typeModels, true);
//
//        File dir = new File(routerProcessor.GROUTER_SOURCE_PATH);
//        if (!dir.exists()) {
//            dir.mkdir();
//        }
//        try {
//            dir = new File(dir, "com/grouter");
//            File file = new File(dir, "RouterTask-" + routerProcessor.MODULE_NAME + ".json");
//            FileWriter fileWriter = new FileWriter(file);
//            fileWriter.write(json);
//            fileWriter.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return typeModels;
    }
 
Example 17
Source File: ComponentBodyGenerator.java    From litho with Apache License 2.0 4 votes vote down vote up
static String getEventHandlerInstanceName(ClassName eventHandlerClassName) {
  final String eventHandlerName = eventHandlerClassName.simpleName();
  return eventHandlerName.substring(0, 1).toLowerCase(Locale.ROOT)
      + eventHandlerName.substring(1)
      + "Handler";
}
 
Example 18
Source File: ReactModuleSpecProcessor.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  Set<? extends Element> reactModuleListElements = roundEnv.getElementsAnnotatedWith(
    ReactModuleList.class);
  for (Element reactModuleListElement : reactModuleListElements) {
    if (!(reactModuleListElement instanceof TypeElement)) {
      continue;
    }

    TypeElement typeElement = (TypeElement) reactModuleListElement;
    ReactModuleList reactModuleList = typeElement.getAnnotation(ReactModuleList.class);

    if (reactModuleList == null) {
      continue;
    }

    ClassName className = ClassName.get(typeElement);
    String packageName = ClassName.get(typeElement).packageName();
    String fileName = className.simpleName();

    List<String> nativeModules = new ArrayList<>();
    try {
      reactModuleList.nativeModules(); // throws MirroredTypesException
    } catch (MirroredTypesException mirroredTypesException) {
      List<? extends TypeMirror> typeMirrors = mirroredTypesException.getTypeMirrors();
      for (TypeMirror typeMirror : typeMirrors) {
        nativeModules.add(typeMirror.toString());
      }
    }

    MethodSpec getReactModuleInfosMethod;
    try {
      getReactModuleInfosMethod = MethodSpec.methodBuilder("getReactModuleInfos")
        .addAnnotation(Override.class)
        .addModifiers(PUBLIC)
        .addCode(getCodeBlockForReactModuleInfos(nativeModules))
        .returns(MAP_TYPE)
        .build();
    } catch (ReactModuleSpecException reactModuleSpecException) {
      mMessager.printMessage(ERROR, reactModuleSpecException.mMessage);
      return false;
    }

    TypeSpec reactModulesInfosTypeSpec = TypeSpec.classBuilder(
      fileName + "$$ReactModuleInfoProvider")
      .addModifiers(Modifier.PUBLIC)
      .addMethod(getReactModuleInfosMethod)
      .addSuperinterface(ReactModuleInfoProvider.class)
      .build();

      JavaFile javaFile = JavaFile.builder(packageName, reactModulesInfosTypeSpec)
        .addFileComment("Generated by " + getClass().getName())
        .build();

    try {
      javaFile.writeTo(mFiler);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  return true;
}
 
Example 19
Source File: M2MEntity.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * Works with @BindDaoMany2Many and @BindDao to extract entity name.
 * @param schema 
 *
 * @param daoElement the dao element
 * @return the m 2 M entity
 */
public static M2MEntity extractEntityManagedByDAO(TypeElement daoElement) {
	ClassName entity1 = null;
	ClassName entity2 = null;
	String prefixId = null;
	String tableName = null;
	String entityName = null;
	PackageElement pkg = null;
	String packageName = null;
	boolean needToCreate = true;
	boolean generatedMethods=true;
	boolean immutable=true;
	
	
	if (daoElement.getAnnotation(BindDaoMany2Many.class) != null) {
		entity1 = TypeUtility.className(AnnotationUtility.extractAsClassName(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_1));
		entity2 = TypeUtility.className(AnnotationUtility.extractAsClassName(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_2));
		prefixId = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ID_NAME);
		tableName = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.TABLE_NAME);
		tableName = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.TABLE_NAME);
		immutable = AnnotationUtility.extractAsBoolean(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.IMMUTABLE);
		
		generatedMethods=AnnotationUtility.extractAsBoolean(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.METHODS);
		
		entityName = entity1.simpleName() + entity2.simpleName();
		pkg = BaseProcessor.elementUtils.getPackageOf(daoElement);
		packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
	}

	if (daoElement.getAnnotation(BindDao.class) != null) {
		// we have @BindDao
		String derived = AnnotationUtility.extractAsClassName(daoElement, BindDao.class, AnnotationAttributeType.VALUE);
		ClassName clazz = TypeUtility.className(derived);

		packageName = clazz.packageName();
		entityName = clazz.simpleName();

		String tableTemp = AnnotationUtility.extractAsClassName(daoElement, BindDao.class, AnnotationAttributeType.TABLE_NAME);
		if (StringUtils.hasText(tableTemp)) {
			tableName = tableTemp;
		}

		needToCreate = false;
	}

	M2MEntity entity = new M2MEntity(daoElement, packageName, entityName, TypeUtility.className(daoElement.asType().toString()), entity1, entity2, prefixId, tableName, needToCreate, generatedMethods, immutable);

	return entity;
}