Java Code Examples for com.squareup.javapoet.TypeName#get()

The following examples show how to use com.squareup.javapoet.TypeName#get() . 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: Field.java    From kvs-schema with MIT License 6 votes vote down vote up
public Field(Element element, Key key) {
    this.prefKeyName = key.name();

    try {
        Class clazz = key.serializer();
        serializerType = TypeName.get(clazz);
        serializeType = detectSerializeTypeNameByClass(clazz);
    } catch (MirroredTypeException mte) {
        DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();
        TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
        serializerType = TypeName.get(classTypeMirror);
        serializeType = detectSerializeTypeByTypeElement(classTypeElement);
    }

    VariableElement variable = (VariableElement) element;
    this.fieldType = TypeName.get(element.asType());
    this.name = element.getSimpleName().toString();
    this.value = variable.getConstantValue();
}
 
Example 2
Source File: ConfigProcessor.java    From AndServer with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    mFiler = processingEnv.getFiler();
    mElements = processingEnv.getElementUtils();
    mLog = new Logger(processingEnv.getMessager());

    mContext = TypeName.get(mElements.getTypeElement(Constants.CONTEXT_TYPE).asType());
    mCollectionUtils = TypeName.get(mElements.getTypeElement(Constants.COLLECTION_UTIL_TYPE).asType());
    mOnRegisterType = TypeName.get(mElements.getTypeElement(Constants.ON_REGISTER_TYPE).asType());
    mRegisterType = TypeName.get(mElements.getTypeElement(Constants.REGISTER_TYPE).asType());

    mConfig = TypeName.get(mElements.getTypeElement(Constants.CONFIG_TYPE).asType());
    mDelegate = TypeName.get(mElements.getTypeElement(Constants.CONFIG_DELEGATE_TYPE).asType());
    mWebsite = TypeName.get(mElements.getTypeElement(Constants.WEBSITE_TYPE).asType());
    mMultipart = TypeName.get(mElements.getTypeElement(Constants.CONFIG_MULTIPART_TYPE).asType());

    mString = TypeName.get(String.class);
}
 
Example 3
Source File: CodeGenerator.java    From toothpick with Apache License 2.0 5 votes vote down vote up
protected TypeName getParamType(ParamInjectionTarget paramInjectionTarget) {
  if (paramInjectionTarget.kind == ParamInjectionTarget.Kind.INSTANCE) {
    return TypeName.get(typeUtil.erasure(paramInjectionTarget.memberClass.asType()));
  } else {
    return ParameterizedTypeName.get(
        ClassName.get(paramInjectionTarget.memberClass),
        ClassName.get(typeUtil.erasure(paramInjectionTarget.kindParamClass.asType())));
  }
}
 
Example 4
Source File: ButterKnifeProcessor.java    From AndroidAll with Apache License 2.0 5 votes vote down vote up
private void parseRoundEnvironment(RoundEnvironment roundEnv) {

        Map<TypeElement, BindClass> map = new LinkedHashMap<>();
        for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) {
            TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
            //所在类名 String className = enclosingElement.getSimpleName().toString();
            //所在类全名 String qualifiedName = enclosingElement.getQualifiedName().toString();
            //注解的值
            int annotationValue = element.getAnnotation(BindView.class).value();

            BindClass bindClass = map.get(enclosingElement);
            if (bindClass == null) {
                bindClass = BindClass.createBindClass(enclosingElement);
                map.put(enclosingElement, bindClass);
            }
            String name = element.getSimpleName().toString();
            TypeName type = TypeName.get(element.asType());
            ViewBinding viewBinding = ViewBinding.createViewBind(name, type, annotationValue);
            bindClass.addAnnotationField(viewBinding);

            //printElement(element);
        }


        for (Map.Entry<TypeElement, BindClass> entry : map.entrySet()) {
            printValue("==========" + entry.getValue().getBindingClassName());
            try {
                entry.getValue().preJavaFile().writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
 
Example 5
Source File: RouterProcessor.java    From JIMU with Apache License 2.0 5 votes vote down vote up
/**
 * create init host method
 */
private MethodSpec generateInitHostMethod() {
    TypeName returnType = TypeName.get(type_String);

    MethodSpec.Builder openUriMethodSpecBuilder = MethodSpec.methodBuilder("getHost")
            .returns(returnType)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC);

    openUriMethodSpecBuilder.addStatement("return $S", host);

    return openUriMethodSpecBuilder.build();
}
 
Example 6
Source File: EntityPartGenerator.java    From requery with Apache License 2.0 5 votes vote down vote up
TypeName guessAnyTypeName(String packageName, TypeMirror mirror) {
    String name = mirror.toString();
    if (name.startsWith("<any?>.")) {
        return ClassName.get(packageName, name.substring("<any?>.".length()));
    } else {
        return TypeName.get(mirror);
    }
}
 
Example 7
Source File: BaseMatchMethodPermutationBuilder.java    From motif with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the statement arguments for the match method matcher statement.
 */
protected static Object[] getMatcherStatementArgs(int matchedCount) {
  TypeName matcher = ParameterizedTypeName.get(ClassName.get(Matcher.class), TypeName.OBJECT);
  TypeName listOfMatchers = ParameterizedTypeName.get(ClassName.get(List.class), matcher);
  TypeName lists = TypeName.get(Lists.class);
  TypeName argumentMatchers = TypeName.get(ArgumentMatchers.class);

  return Stream.concat(
      ImmutableList.of(listOfMatchers, lists).stream(),
      IntStream.range(0, matchedCount)
          .mapToObj(i -> argumentMatchers)
  ).toArray(s -> new TypeName[s]);
}
 
Example 8
Source File: PaperParcelWriter.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
private void writeField(
    MethodSpec.Builder builder,
    FieldDescriptor field,
    CodeBlock accessorBlock,
    ParameterSpec dest,
    ParameterSpec flags) {
  TypeName fieldTypeName = TypeName.get(field.type().get());
  if (fieldTypeName.isPrimitive()) {
    if (TypeName.BOOLEAN.equals(fieldTypeName)) {
      builder.addStatement("$N.writeInt($L ? 1 : 0)", dest, accessorBlock);
    } else if (TypeName.INT.equals(fieldTypeName)) {
      builder.addStatement("$N.writeInt($L)", dest, accessorBlock);
    } else if (TypeName.LONG.equals(fieldTypeName)) {
      builder.addStatement("$N.writeLong($L)", dest, accessorBlock);
    } else if (TypeName.DOUBLE.equals(fieldTypeName)) {
      builder.addStatement("$N.writeDouble($L)", dest, accessorBlock);
    } else if (TypeName.FLOAT.equals(fieldTypeName)) {
      builder.addStatement("$N.writeFloat($L)", dest, accessorBlock);
    } else if (TypeName.CHAR.equals(fieldTypeName)) {
      builder.addStatement("$N.writeInt($L)", dest, accessorBlock);
    } else if (TypeName.BYTE.equals(fieldTypeName)) {
      builder.addStatement("$N.writeByte($L)", dest, accessorBlock);
    } else if (TypeName.SHORT.equals(fieldTypeName)) {
      builder.addStatement("$N.writeInt($L)", dest, accessorBlock);
    } else {
      throw new IllegalArgumentException("Unknown primitive type: " + fieldTypeName);
    }
  } else {
    AdapterDescriptor adapter = descriptor.adapters().get(field);
    CodeBlock adapterInstance = adapterInstance(adapter);
    if (field.isNullable() && !adapter.nullSafe()) {
      builder.addStatement("$T.writeNullable($L, $N, $N, $L)",
          UTILS, accessorBlock, dest, flags, adapterInstance);
    } else {
      builder.addStatement("$L.writeToParcel($L, $N, $N)",
          adapterInstance, accessorBlock, dest, flags);
    }
  }
}
 
Example 9
Source File: JniProcessor.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
TypeName toTypeName(TypeMirror t, boolean useJni) {
    if (t.getKind() == TypeKind.ARRAY) {
        return ArrayTypeName.of(toTypeName(((ArrayType) t).getComponentType(), useJni));
    }
    TypeName typeName = TypeName.get(t);
    if (useJni && shouldDowncastToObjectForJni(typeName)) {
        return TypeName.OBJECT;
    }
    return typeName;
}
 
Example 10
Source File: SolidityFunctionWrapper.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static TypeName getNativeType(TypeName typeName) {

        if (typeName instanceof ParameterizedTypeName) {
            return getNativeType((ParameterizedTypeName) typeName);
        }

        String simpleName = ((ClassName) typeName).simpleName();

        if (simpleName.startsWith(Address.class.getSimpleName())) {
            return TypeName.get(String.class);
        } else if (simpleName.startsWith("Uint")) {
            return TypeName.get(BigInteger.class);
        } else if (simpleName.startsWith("Int")) {
            return TypeName.get(BigInteger.class);
        } else if (simpleName.startsWith(Utf8String.class.getSimpleName())) {
            return TypeName.get(String.class);
        } else if (simpleName.startsWith("Bytes")) {
            return TypeName.get(byte[].class);
        } else if (simpleName.startsWith(DynamicBytes.class.getSimpleName())) {
            return TypeName.get(byte[].class);
        } else if (simpleName.startsWith(Bool.class.getSimpleName())) {
            return TypeName.get(Boolean.class); // boolean cannot be a parameterized type
        } else {
            throw new UnsupportedOperationException(
                    "Unsupported type: " + typeName + ", no native type mapping exists.");
        }
    }
 
Example 11
Source File: CursorHelperGenerator.java    From Freezer with Apache License 2.0 5 votes vote down vote up
public CursorHelperGenerator(Element element) {
    this.element = element;
    this.objectName = ProcessUtils.getObjectName(element);
    this.modelType = TypeName.get(element.asType());
    this.fields = ProcessUtils.getPrimitiveFields(element);
    this.otherClassFields = ProcessUtils.getNonPrimitiveClassFields(element);
    this.collections = ProcessUtils.getCollectionsOfPrimitiveFields(element);
}
 
Example 12
Source File: PatchDtoGenerator.java    From pnc with Apache License 2.0 5 votes vote down vote up
public static TypeName[] getGenericTypeNames(VariableElement field) {
    TypeMirror fieldType = field.asType();
    List<? extends TypeMirror> typeArguments = ((DeclaredType) fieldType).getTypeArguments();
    TypeName[] typeNames = new TypeName[typeArguments.size()];
    for (int i = 0; i < typeArguments.size(); i++) {
        typeNames[i] = TypeName.get(typeArguments.get(i));
    }
    return typeNames;
}
 
Example 13
Source File: StateProperty.java    From reductor with Apache License 2.0 5 votes vote down vote up
public TypeName getReducerInterfaceTypeName() {
    TypeName stateType = TypeName.get(this.stateType);
    if (stateType.isPrimitive()) {
        stateType = stateType.box();
    }
    return ParameterizedTypeName.get(ClassName.get(Reducer.class), stateType);
}
 
Example 14
Source File: SolidityFunctionWrapper.java    From web3j with Apache License 2.0 5 votes vote down vote up
static TypeName getEventNativeType(TypeName typeName) {
    if (typeName instanceof ParameterizedTypeName) {
        return TypeName.get(byte[].class);
    }

    String simpleName = ((ClassName) typeName).simpleName();
    if (simpleName.equals(Utf8String.class.getSimpleName())) {
        return TypeName.get(byte[].class);
    } else {
        return getNativeType(typeName);
    }
}
 
Example 15
Source File: FieldData.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
public TypeName getTypeName(){
    return TypeName.get(tm);
}
 
Example 16
Source File: ColumnProperty.java    From auto-value-cursor with Apache License 2.0 4 votes vote down vote up
public ClassName columnAdapter() {
    TypeMirror mirror = (TypeMirror) getAnnotationValue(element(), ColumnAdapter.class, "value");
    return mirror != null ? (ClassName) TypeName.get(mirror) : null;
}
 
Example 17
Source File: XModuleProcessor.java    From XModulable with Apache License 2.0 4 votes vote down vote up
/**
 * 生成源码,主要由三个步骤
 * <ol>
 * <li>创建方法</li>
 * <li>创建类</li>
 * <li>输出源文件</li>
 * </ol>
 *
 * @param moduleElements key:组件名;value:携带@XModule的Element
 */
private void generateCode(Map<String, Element> moduleElements) throws ProcessException {
    if (moduleElements == null || moduleElements.isEmpty()) {
        return;
    }

    /*
    1、创建方法
    public void loadInto(XModulableOptions options) {
           if (options == null) {
               return;
           }
           options.addModule(, );
     }
     */
    MethodSpec.Builder loadIntoMethod = MethodSpec.methodBuilder(Constants.METHOD_OF_LOAD_INTO)
            .addJavadoc("向$N添加组件", Constants.PARAMETER_OF_XMODULABLE_OPTIONS)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ClassName.get(mElementUtils.getTypeElement(Constants.XMODULABLE_OPTIONS)), Constants.PARAMETER_OF_XMODULABLE_OPTIONS)
            .returns(void.class)
            .beginControlFlow("if ($N == null)", Constants.PARAMETER_OF_XMODULABLE_OPTIONS)
            .addStatement("return")
            .endControlFlow();
    for (Map.Entry<String, Element> entry : moduleElements.entrySet()) {
        String moduleName = entry.getKey();
        TypeName moduleTypeName = TypeName.get(entry.getValue().asType()); // 注解的宿主类型名
        loadIntoMethod.addStatement("$N.addModule($S, new $T())", Constants.PARAMETER_OF_XMODULABLE_OPTIONS, moduleName, moduleTypeName);
    }
    mLogger.info(String.format("创建方法:%s", Constants.METHOD_OF_LOAD_INTO));

    /*
    2、创建类
    public final class XModule$$Loader$$组件名 implements XModuleLoader
     */
    String className = new StringBuilder()
            .append(Constants.SDK_NAME)
            .append(Constants.SEPARATOR_OF_CLASS_NAME)
            .append(Constants.CLASS_OF_LOADER)
            .append(Constants.SEPARATOR_OF_CLASS_NAME)
            .append(mModuleName)
            .toString();
    TypeSpec.Builder componentLoader = TypeSpec.classBuilder(className)
            .addJavadoc(
                    new StringBuilder()
                            .append("$N组件加载器")
                            .append("\n")
                            .append("<ul><li>")
                            .append(Constants.WARNING_TIPS)
                            .append("</li></ul>")
                            .append("\n@author $N")
                            .toString(),
                    mModuleName,
                    XModuleProcessor.class.getSimpleName())
            .addSuperinterface(ClassName.get(mXModuleLoader))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(loadIntoMethod.build());
    mLogger.info(String.format("创建类:%s", className));

    /*
    3、输出源文件
    XModule$$Loader$$组件名.java
     */
    try {
        JavaFile.builder(Constants.PACKAGE_OF_GENERATE, componentLoader.build())
                .build().writeTo(mFiler);
        mLogger.info(String.format("输出源文件:%s", Constants.PACKAGE_OF_GENERATE + "." + className + ".java"));
    } catch (IOException e) {
        throw new ProcessException(e.fillInStackTrace());
    }
}
 
Example 18
Source File: WriterUtil.java    From sqlitemagic with Apache License 2.0 4 votes vote down vote up
public static TypeName typeName(@NonNull TypeMirror type) {
  return TypeName.get(type);
}
 
Example 19
Source File: DataBindingInfo.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
public TypeName getBinderFactoryClass() {
    return binderFactoryClass == null ? null :TypeName.get(binderFactoryClass);
}
 
Example 20
Source File: ButterKnifeProcessor.java    From butterknife with Apache License 2.0 4 votes vote down vote up
private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
    Set<TypeElement> erasedTargetNames) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Start by verifying common generated code restrictions.
  boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element)
      || isBindingInWrongPackage(BindView.class, element);

  // Verify that the target type extends from View.
  TypeMirror elementType = element.asType();
  if (elementType.getKind() == TypeKind.TYPEVAR) {
    TypeVariable typeVariable = (TypeVariable) elementType;
    elementType = typeVariable.getUpperBound();
  }
  Name qualifiedName = enclosingElement.getQualifiedName();
  Name simpleName = element.getSimpleName();
  if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) {
    if (elementType.getKind() == TypeKind.ERROR) {
      note(element, "@%s field with unresolved type (%s) "
              + "must elsewhere be generated as a View or interface. (%s.%s)",
          BindView.class.getSimpleName(), elementType, qualifiedName, simpleName);
    } else {
      error(element, "@%s fields must extend from View or be an interface. (%s.%s)",
          BindView.class.getSimpleName(), qualifiedName, simpleName);
      hasError = true;
    }
  }

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  int id = element.getAnnotation(BindView.class).value();
  BindingSet.Builder builder = builderMap.get(enclosingElement);
  Id resourceId = elementToId(element, BindView.class, id);
  if (builder != null) {
    String existingBindingName = builder.findExistingBindingName(resourceId);
    if (existingBindingName != null) {
      error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
          BindView.class.getSimpleName(), id, existingBindingName,
          enclosingElement.getQualifiedName(), element.getSimpleName());
      return;
    }
  } else {
    builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  }

  String name = simpleName.toString();
  TypeName type = TypeName.get(elementType);
  boolean required = isFieldRequired(element);

  builder.addField(resourceId, new FieldViewBinding(name, type, required));

  // Add the type-erased version to the valid binding targets set.
  erasedTargetNames.add(enclosingElement);
}