com.squareup.javapoet.ArrayTypeName Java Examples

The following examples show how to use com.squareup.javapoet.ArrayTypeName. 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: MethodRouterGenerator.java    From componentrouter with Apache License 2.0 7 votes vote down vote up
private void addArrConvertMethod(TypeSpec.Builder builder, Map<String, String> arrConvertMap) {
    for (Map.Entry<String, String> entry : arrConvertMap.entrySet()) {
        String methodName = entry.getKey();
        String type = entry.getValue();

        TypeName typeName = TypeNameUtils.getTypeName(type.replace("[]", ""));
        ArrayTypeName arrayTypeName = ArrayTypeName.of(typeName);
        System.out.println(arrayTypeName);
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName)
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
                .addParameter(Object[].class, "objs")
                .returns(arrayTypeName)
                .addStatement("$T arr=new $T[objs.length]", arrayTypeName, typeName);
        methodBuilder.beginControlFlow("for(int i = 0;i<objs.length;i++)")
                .addStatement("arr[i]=($T)objs[i]", typeName)
                .endControlFlow();
        methodBuilder.addStatement("return arr");
        builder.addMethod(methodBuilder.build());
    }
}
 
Example #2
Source File: BindTableGenerator.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * generate columns array.
 *
 * @param entity
 *            the entity
 */
private void generateColumnsArray(Finder<SQLProperty> entity) {
	// generate columns array
	Builder sp = FieldSpec.builder(ArrayTypeName.of(String.class), "COLUMNS", Modifier.STATIC, Modifier.PRIVATE,
			Modifier.FINAL);
	String s = "";
	StringBuilder buffer = new StringBuilder();
	for (SQLProperty property : entity.getCollection()) {
		buffer.append(s + "COLUMN_" + columnNameToUpperCaseConverter.convert(property.getName()));
		s = ", ";
	}
	classBuilder.addField(sp.addJavadoc("Columns array\n").initializer("{" + buffer.toString() + "}").build());
	classBuilder.addMethod(MethodSpec.methodBuilder("columns").addModifiers(Modifier.PUBLIC)
			.addJavadoc("Columns array\n").addAnnotation(Override.class).returns(ArrayTypeName.of(String.class))
			.addStatement("return COLUMNS").build());

	classBuilder.addMethod(MethodSpec.methodBuilder("name").addModifiers(Modifier.PUBLIC).addJavadoc("table name\n")
			.addAnnotation(Override.class).returns(TypeName.get(String.class)).addStatement("return TABLE_NAME")
			.build());
}
 
Example #3
Source File: DatabaseHelperCreator.java    From AirData with MIT License 6 votes vote down vote up
private MethodSpec generateDeleteMethod() {
    MethodSpec.Builder saveMethodBuidler = MethodSpec.methodBuilder("delete")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.INT)
            .addParameter(ClassName.get(Class.class), "clazz")
            .addParameter(ClassName.get(String.class), "where")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "whereArgs");

    for (TableInfo table : tables) {

        String daoField = table.getDaoClassName().replace("$$", "").toLowerCase();

        saveMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.delete(where, whereArgs)", table.getClassName(), daoField);
    }

    saveMethodBuidler.addStatement("return 0");
    return saveMethodBuidler.build();
}
 
Example #4
Source File: DatabaseHelperCreator.java    From AirData with MIT License 6 votes vote down vote up
private MethodSpec generateRawQueryMethod() {
    MethodSpec.Builder queryMethodBuidler = MethodSpec.methodBuilder("rawQuery")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(ClassName.get("android.database", "Cursor"))
            .addParameter(ClassName.get(Class.class), "clazz")
            .addParameter(TypeName.BOOLEAN, "distinct")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns")
            .addParameter(ClassName.get(String.class), "selection")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs")
            .addParameter(ClassName.get(String.class), "groupBy")
            .addParameter(ClassName.get(String.class), "having")
            .addParameter(ClassName.get(String.class), "orderBy")
            .addParameter(ClassName.get(String.class), "limit");

    for (TableInfo table : tables) {

        String daoField = table.getDaoClassName().replace("$$", "").toLowerCase();

        queryMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.rawQuery(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", table.getClassName(), daoField);
    }

    queryMethodBuidler.addStatement("return null");
    return queryMethodBuidler.build();
}
 
Example #5
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 #6
Source File: DatabaseHelperCreator.java    From AirData with MIT License 6 votes vote down vote up
private MethodSpec generateUpdateMethod() {
    MethodSpec.Builder saveMethodBuidler = MethodSpec.methodBuilder("update")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.INT)
            .addParameter(ClassName.get(Class.class), "clazz")
            .addParameter(ClassName.get(ContentValuesWrapper.class), "valuesWrapper")
            .addParameter(ClassName.get(String.class), "where")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "whereArgs");

    for (TableInfo table : tables) {

        String daoField = table.getDaoClassName().replace("$$", "").toLowerCase();
        saveMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.update(valuesWrapper, where, whereArgs)", table.getClassName(), daoField);
    }

    saveMethodBuidler.addStatement("return 0");
    return saveMethodBuidler.build();
}
 
Example #7
Source File: TypeUtils.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
/**
 * @return int/long/float/double/boolean/
 * Integer/Long/Double/Float/Boolean/String/
 * int[]/long[]/float[]/double[]/boolean[]/Object[]/String[]
 * Activity/Context/Application/Object/Map/HashMap/List/ArrayList
 */
public static String getRouterActivityTypeString(TypeName typeName) {
    // 判断是否泛型
    if (typeName instanceof ParameterizedTypeName) {
        typeName = ((ParameterizedTypeName) typeName).rawType;
    }
    // 获取支持支持的类型
    if (baseTypeNameSet.contains(typeName)) {
        return typeName.toString();
    }
    // 判断是否数组
    else if (typeName instanceof ArrayTypeName) {
        return "Object[]";
    } else {
        return "Object";
    }
}
 
Example #8
Source File: DAOCreator.java    From AirData with MIT License 6 votes vote down vote up
private MethodSpec generatorQueryMethod() {
    MethodSpec.Builder queryBuilder = MethodSpec.methodBuilder("query")
            .addModifiers(Modifier.PUBLIC)
            .returns(ClassName.get(List.class))
            .addParameter(TypeName.BOOLEAN, "distinct")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns")
            .addParameter(ClassName.get(String.class), "selection")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs")
            .addParameter(ClassName.get(String.class), "groupBy")
            .addParameter(ClassName.get(String.class), "having")
            .addParameter(ClassName.get(String.class), "orderBy")
            .addParameter(ClassName.get(String.class), "limit")
            .addStatement("$T cursor = this.rawQuery(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", ClassName.get("android.database", "Cursor"));
    queryBuilder.addStatement("$T list = new $T()", ArrayList.class, ArrayList.class);
    queryBuilder.addCode("if (cursor.moveToFirst()) {");
    queryBuilder.addCode("  do {");
    queryBuilder.addCode("     list.add(fillData(cursor));");
    queryBuilder.addCode("  } while (cursor.moveToNext());");
    queryBuilder.addCode("}");
    queryBuilder.addStatement("return list");
    return queryBuilder.build();
}
 
Example #9
Source File: TypeUtils.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
public static String getRouterTaskTypeString(TypeName typeName) {
    // 判断是否泛型
    if (typeName instanceof ParameterizedTypeName) {
        typeName = ((ParameterizedTypeName) typeName).rawType;
    }
    // 获取支持支持的类型
    if (baseTypeNameSet.contains(typeName)) {
        return typeName.toString();
    }
    // 判断是否数组
    else if (typeName instanceof ArrayTypeName) {
        typeName = ((ArrayTypeName) typeName).componentType;
        return getRouterTaskTypeString(typeName) + "[]";
    } else {
        String typeNameString = typeName.toString();
        if (typeNameString.startsWith("android") || typeNameString.startsWith("java")) {
            return typeNameString;
        }
        return "Object";
    }
}
 
Example #10
Source File: VarArgSetterSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
MethodSpec buildSignature(RDFSClazz domainClazz, OntGenerationConfig config) throws RepositoryException {
    if (getRanges() != null) {
        MethodSpec.Builder setter = buildParameterlessSetterSignature(domainClazz, config);

        // Get the vararg parameter type:
        TypeName paramType = ArrayTypeName.of(getParameterType(config, false));


        return setter.addParameter(paramType, "values")
                     .varargs()
                     .build();
    } else {
        return null;
    }
}
 
Example #11
Source File: OutputValueFactory.java    From dataenum with Apache License 2.0 6 votes vote down vote up
private static boolean typeNeedsTypeVariable(TypeName type, TypeVariableName typeVariable) {
  if (typeVariable.equals(type)) {
    return true;
  }

  if (type instanceof ParameterizedTypeName) {
    ParameterizedTypeName parameterized = ((ParameterizedTypeName) type);
    for (TypeName typeArgument : parameterized.typeArguments) {
      if (typeVariable.equals(typeArgument)) {
        return true;
      }
      if (typeNeedsTypeVariable(typeArgument, typeVariable)) {
        return true;
      }
    }
  }

  if (type instanceof ArrayTypeName) {
    ArrayTypeName arrayType = (ArrayTypeName) type;
    if (typeVariable.equals(arrayType.componentType)) {
      return true;
    }
  }
  return false;
}
 
Example #12
Source File: TypeUtils.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
/**
 * @return int/long/float/double/boolean/
 * Integer/Long/Double/Float/Boolean/String/
 * int[]/long[]/float[]/double[]/boolean[]/Object[]/String[]
 * Activity/Context/Application/Object/Map/HashMap/List/ArrayList
 */
public static String getRouterActivityTypeString(TypeName typeName) {
    // 判断是否泛型
    if (typeName instanceof ParameterizedTypeName) {
        typeName = ((ParameterizedTypeName) typeName).rawType;
    }
    // 获取支持支持的类型
    if (baseTypeNameSet.contains(typeName)) {
        return typeName.toString();
    }
    // 判断是否数组
    else if (typeName instanceof ArrayTypeName) {
        return "Object[]";
    } else {
        return "Object";
    }
}
 
Example #13
Source File: TypeUtility.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a TypeMirror in a typeName.
 *
 * @param typeMirror
 *            the type mirror
 * @return typeName
 */
public static TypeName typeName(TypeMirror typeMirror) {
	LiteralType literalType = LiteralType.of(typeMirror.toString());

	if (literalType.isArray()) {
		return ArrayTypeName.of(typeName(literalType.getRawType()));
	} else if (literalType.isCollection()) {
		return ParameterizedTypeName.get(TypeUtility.className(literalType.getRawType()),
				typeName(literalType.getTypeParameter()));
	}

	TypeName[] values = { TypeName.BOOLEAN, TypeName.BYTE, TypeName.CHAR, TypeName.DOUBLE, TypeName.FLOAT,
			TypeName.INT, TypeName.LONG, TypeName.SHORT, TypeName.VOID };

	for (TypeName item : values) {
		if (typeMirror.toString().equals(item.toString())) {
			return item;
		}
	}

	return TypeName.get(typeMirror);
}
 
Example #14
Source File: TypeUtils.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
public static String getRouterTaskTypeString(TypeName typeName) {
    // 判断是否泛型
    if (typeName instanceof ParameterizedTypeName) {
        typeName = ((ParameterizedTypeName) typeName).rawType;
    }
    // 获取支持支持的类型
    if (baseTypeNameSet.contains(typeName)) {
        return typeName.toString();
    }
    // 判断是否数组
    else if (typeName instanceof ArrayTypeName) {
        typeName = ((ArrayTypeName) typeName).componentType;
        return getRouterTaskTypeString(typeName) + "[]";
    } else {
        String typeNameString = typeName.toString();
        if (typeNameString.startsWith("android") || typeNameString.startsWith("java")) {
            return typeNameString;
        }
        return "Object";
    }
}
 
Example #15
Source File: BeanJsonSerializerCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private MethodSpec buildInitSerializersMethod( Map<PropertyInfo, JSerializerType> properties )
        throws UnableToCompleteException {
    MethodSpec.Builder builder = MethodSpec.methodBuilder( "initSerializers" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ArrayTypeName.of( BeanPropertySerializer.class ) )
            .addStatement( "$T result = new $T[$L]",
                    ArrayTypeName.of( BeanPropertySerializer.class ), BeanPropertySerializer.class, properties.size() );

    int i = 0;
    for ( Entry<PropertyInfo, JSerializerType> entry : properties.entrySet() ) {
        builder.addStatement( "result[$L] = $L", i++, buildSerializer( entry.getKey(), entry.getValue() ) );
    }

    builder.addStatement( "return result" );
    return builder.build();
}
 
Example #16
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
public static String getArgsType(ParameterizedTypeName parameterizedTypeName) {
	StringBuilder builder = new StringBuilder();
	for (int i = 0; i < parameterizedTypeName.typeArguments.size(); i++) {
		TypeName argType = parameterizedTypeName.typeArguments.get(i);
		if (argType instanceof ParameterizedTypeName) {
			builder.append(getParameterizedType((ParameterizedTypeName) argType));
		} else {
			if (argType instanceof ArrayTypeName) {
				builder.append(((ArrayTypeName) argType).toString() + ".class");
			} else {
				builder.append(((ClassName) argType).toString() + ".class");
			}
		}
		if (i < parameterizedTypeName.typeArguments.size() - 1) {
			builder.append(", ");
		}
	}
	return builder.toString();
}
 
Example #17
Source File: AnnotatedDurableEntityClass.java    From mnemonic with Apache License 2.0 6 votes vote down vote up
protected void genNFieldInfo() {
  FieldInfo dynfieldinfo, fieldinfo;
  List<long[]> finfo = new ArrayList<long[]>();
  for (String name : m_gettersinfo.keySet()) {
    dynfieldinfo = m_dynfieldsinfo.get(name);
    if (dynfieldinfo.id > 0) {
      finfo.add(new long[]{dynfieldinfo.id, dynfieldinfo.fieldoff, dynfieldinfo.fieldsize});
    }
  }

  fieldinfo = new FieldInfo();
  fieldinfo.name = String.format("m_nfieldinfo_%s", Utils.genRandomString());
  fieldinfo.type = ArrayTypeName.of(ArrayTypeName.of(TypeName.LONG));
  String initlstr = Utils.toInitLiteral(finfo);
  fieldinfo.specbuilder = FieldSpec.builder(fieldinfo.type, fieldinfo.name, Modifier.PRIVATE, Modifier.STATIC)
      .initializer("$1L", initlstr);
  m_fieldsinfo.put("nfieldinfo", fieldinfo);
}
 
Example #18
Source File: SQLiteDAOClass.java    From HighLite with Apache License 2.0 6 votes vote down vote up
private MethodSpec buildGetSingleByRawQueryMethod() {
    final String cursorVarName = "cursor";
    return MethodSpec.methodBuilder("getSingle")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(getClassNameOfElement())
            .addParameter(CONTEXT, "context", Modifier.FINAL)
            .addParameter(STRING, "rawQueryClause", Modifier.FINAL)
            .addParameter(ArrayTypeName.of(STRING), "rawQueryArgs", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchForeignKeys", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchRelationships", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL)
            .addStatement("final $T $L = getReadableDatabase($L)"
                            + ".rawQuery(rawQueryClause, rawQueryArgs)",
                    CURSOR, cursorVarName, "context")
            .beginControlFlow("if (!$L.moveToFirst())", cursorVarName)
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return null")
            .endControlFlow()
            .addStatement("$T ret = instantiateObject(cursor, context, "
                            + "fetchForeignKeys, fetchRelationships, fromCache)",
                    getClassNameOfElement())
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return ret")
            .build();
}
 
Example #19
Source File: PsiTypeUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
static TypeName getTypeName(PsiType type) {
  if (type instanceof PsiPrimitiveType) {
    // float
    return getPrimitiveTypeName((PsiPrimitiveType) type);
  } else if (type instanceof PsiClassType && ((PsiClassType) type).getParameterCount() > 0) {
    // Set<Integer>
    PsiClassType classType = (PsiClassType) type;
    return ParameterizedTypeName.get(
        guessClassName(classType.rawType().getCanonicalText()),
        getTypeNameArray(classType.getParameters()));
  } else if (type instanceof PsiArrayType) {
    // int[]
    PsiType componentType = ((PsiArrayType) type).getComponentType();
    return ArrayTypeName.of(getTypeName(componentType));
  } else if (type.getCanonicalText().contains("?")) {
    // ? extends Type
    return getWildcardTypeName(type.getCanonicalText());
  } else {
    return guessClassName(type.getCanonicalText());
  }
}
 
Example #20
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionVarargSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName itemType = genericArgument(d, field, 0);

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ArrayTypeName.of(itemType), fieldName)
      .varargs()
      .returns(builderType(d));

  ensureSafeVarargs(setter);

  collectionNullGuard(setter, field);

  setter.addStatement("return $N($T.asList($N))", fieldName, ClassName.get(Arrays.class), fieldName);
  return setter.build();
}
 
Example #21
Source File: ComponentBodyGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
static TypeSpecDataHolder generateGetDynamicProps(SpecModel specModel) {
  final TypeSpecDataHolder.Builder typeSpecDataHolder = TypeSpecDataHolder.newBuilder();

  if (SpecModelUtils.getDynamicProps(specModel).isEmpty()) {
    return typeSpecDataHolder.build();
  }

  final MethodSpec methodSpec =
      MethodSpec.methodBuilder("getDynamicProps")
          .addModifiers(Modifier.PROTECTED)
          .addAnnotation(Override.class)
          .returns(ArrayTypeName.of(ClassNames.DYNAMIC_VALUE))
          .addStatement("return $L", DYNAMIC_PROPS)
          .build();

  return typeSpecDataHolder.addMethod(methodSpec).build();
}
 
Example #22
Source File: MatcherGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static MethodSpec resWithVarargsBuilder(
    SpecModel specModel,
    final PropModel prop,
    final ClassName annotationClassName,
    final String resolver,
    final TypeName varargsType,
    final String varargsName) {
  return getMethodSpecBuilder(
          specModel,
          prop,
          prop.getName() + "Res",
          Arrays.asList(
              parameter(prop, TypeName.INT, "resId", annotation(annotationClassName)),
              ParameterSpec.builder(ArrayTypeName.of(varargsType), varargsName).build()),
          "$L.$L(resId, " + varargsName + ")",
          RESOURCE_RESOLVER,
          resolver + "Res")
      .varargs(true)
      .build();
}
 
Example #23
Source File: ExtendedTypeElement.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
public TypeName asTypeName() {
  final ClassName className = ClassName.get(getTypeElement());
  if (isArrayElement) {
    return ArrayTypeName.of(className);
  }
  return className;
}
 
Example #24
Source File: SQLiteDAOClass.java    From HighLite with Apache License 2.0 5 votes vote down vote up
private MethodSpec buildGetSingleMethod() {
    final String cursorVarName = "cursor";
    return MethodSpec.methodBuilder("getSingle")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(getClassNameOfElement())
            .addParameter(CONTEXT, "context", Modifier.FINAL)
            .addParameter(STRING, "whereClause", Modifier.FINAL)
            .addParameter(ArrayTypeName.of(STRING), "whereArgs", Modifier.FINAL)
            .addParameter(STRING, "groupBy", Modifier.FINAL)
            .addParameter(STRING, "having", Modifier.FINAL)
            .addParameter(STRING, "orderBy", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchForeignKeys", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchRelationships", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL)
            .addStatement("final String sql = $S \n"
                            + "+ (whereClause != null ? $S + whereClause : $S)\n"
                            + "+ (groupBy != null ? $S + groupBy : $S)\n"
                            + "+ (having != null ? $S + groupBy : $S)\n"
                            + "+ (orderBy != null ? $S + orderBy : $S)\n"
                            + "+ $S",
                    getJoinStatementForFetch(), " WHERE ", "", " GROUP BY ", "", " HAVING ",
                    "", " ORDER BY ", "", " LIMIT 1 ")
            .addStatement("final $T $L = getReadableDatabase($L)"
                            + ".rawQuery(sql, whereArgs)",
                    CURSOR, cursorVarName, "context")
            .beginControlFlow("if (!$L.moveToFirst())", cursorVarName)
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return null")
            .endControlFlow()
            .addStatement("$T ret = instantiateObject(cursor, context, "
                            + "fetchForeignKeys, fetchRelationships, fromCache)",
                    getClassNameOfElement())
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return ret")
            .build();
}
 
Example #25
Source File: SQLiteDAOClass.java    From HighLite with Apache License 2.0 5 votes vote down vote up
private MethodSpec buildGetListByRawQueryMethod() {
    final String cursorVarName = "cursor";
    return MethodSpec.methodBuilder("getList")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(ParameterizedTypeName.get(LIST, getClassNameOfElement()))
            .addParameter(CONTEXT, "context", Modifier.FINAL)
            .addParameter(STRING, "rawQueryClause", Modifier.FINAL)
            .addParameter(ArrayTypeName.of(STRING), "rawQueryArgs", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchForeignKeys", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchRelationships", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL)
            .addStatement("final $T<$T> ret = new $T<>()", LIST, getClassNameOfElement(),
                    ARRAY_LIST)
            .addStatement("final $T $L = getReadableDatabase($L)"
                            + ".rawQuery(rawQueryClause, rawQueryArgs)",
                    CURSOR, cursorVarName, "context")
            .beginControlFlow("if (!$L.moveToFirst())", cursorVarName)
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return ret")
            .endControlFlow()
            .beginControlFlow("do")
            .addStatement("ret.add(instantiateObject(cursor, context, "
                    + "fetchForeignKeys, fetchRelationships, fromCache))")
            .endControlFlow("while(cursor.moveToNext())")
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return ret")
            .build();
}
 
Example #26
Source File: TypeNameUtils.java    From componentrouter with Apache License 2.0 5 votes vote down vote up
public static TypeName getTypeName(String fullClassName) {
    if (fullClassName.contains("[]")) {
        TypeName simpleName = getTypeName(fullClassName.replace("[]", ""));
        return ArrayTypeName.of(simpleName);
    }
    int index = fullClassName.lastIndexOf(".");
    if (index == -1) {
        fullClassName = fullClassName.toLowerCase();
        switch (fullClassName) {
            case "short":
                return TypeName.SHORT;
            case "int":
                return TypeName.INT;
            case "long":
                return TypeName.LONG;
            case "float":
                return TypeName.FLOAT;
            case "double":
                return TypeName.DOUBLE;
            case "char":
                return TypeName.CHAR;
            case "byte":
                return TypeName.BYTE;
            case "boolean":
                return TypeName.BOOLEAN;
            default:
                return TypeName.INT;
        }
    }
    String packageName = fullClassName.substring(0, index);
    String className = fullClassName.replace(packageName, "").replace(".", "");
    return ClassName.get(packageName, className);
}
 
Example #27
Source File: SQLiteDAOClass.java    From HighLite with Apache License 2.0 5 votes vote down vote up
private MethodSpec buildDeleteByQueryMethod() {
    return MethodSpec.methodBuilder("deleteByQuery")
            .returns(TypeName.INT)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(CONTEXT, "context", Modifier.FINAL)
            .addParameter(STRING, "whereClause", Modifier.FINAL)
            .addParameter(ArrayTypeName.of(STRING), "whereArgs", Modifier.FINAL)
            .addStatement("return getWritableDatabase($L)"
                            + ".delete(\n$S, \nwhereClause, \nwhereArgs)",
                    "context", getTableName(mElement))
            .build();
}
 
Example #28
Source File: IntrospectorConstructorInvokerCreator.java    From reflection-no-reflection with Apache License 2.0 5 votes vote down vote up
public MethodSpec createConstructorInvoker(Class<?> aClass) {
    ParameterSpec parameterSpec1 = ParameterSpec.builder(STRING_TYPE_NAME, "signature").build();
    TypeName objectVarArgsType = ArrayTypeName.get(Object[].class);
    ParameterSpec parameterSpec2 = ParameterSpec.builder(objectVarArgsType, "params").build();
    String packageName = aClass.getName().substring(0, aClass.getName().lastIndexOf('.'));
    String className = aClass.getSimpleName();
    MethodSpec.Builder newInstanceMethodBuilder = MethodSpec.methodBuilder("newInstance")
        .addModifiers(Modifier.PUBLIC)
        .addAnnotation(Override.class)
        .addParameter(parameterSpec1)
        .addParameter(parameterSpec2)
        .returns(ClassName.get(packageName, className))
        .addException(InvocationTargetException.class)
        .varargs()
        .returns(OBJECT_TYPE_NAME)
        .addCode("switch(signature) {\n");

    for (Object constructorObj : aClass.getConstructors()) {
        Constructor constructor = (Constructor) constructorObj;
        newInstanceMethodBuilder.addCode("  case($S) :\n", constructor.toString());

        invokeConstructor(aClass, newInstanceMethodBuilder, constructor);

    }
    newInstanceMethodBuilder.addCode("  default :\n");
    newInstanceMethodBuilder.addStatement("throw new InvocationTargetException(new java.lang.NoSuchMethodException(\"constructor:\" + signature + \" not found\"))");
    newInstanceMethodBuilder.addCode("}\n");

    return newInstanceMethodBuilder.build();
}
 
Example #29
Source File: TypeUtility.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if is assignable.
 *
 * @param typeName
 *            the type name
 * @param assignableClazz
 *            the assignable clazz
 * @return true, if is assignable
 */
public static boolean isAssignable(TypeName typeName, Class<?> assignableClazz) {
	try {
		if (typeName instanceof ParameterizedTypeName) {
			typeName = ((ParameterizedTypeName) typeName).rawType;
		} else if (typeName instanceof ArrayTypeName) {
			typeName = ((ArrayTypeName) typeName).componentType;
		}

		Class<?> resolvedType = Class.forName(typeName.toString());
		return assignableClazz.isAssignableFrom(resolvedType);
	} catch (ClassNotFoundException e) {
		return false;
	}
}
 
Example #30
Source File: AnnotationCreatorClassPoolVisitor.java    From reflection-no-reflection with Apache License 2.0 5 votes vote down vote up
private JavaFile buildAnnotationImpl(Class<? extends Annotation> annotationClass) {
    String aClassName = annotationClass.getName();
    MethodSpec annotationTypeMethod = MethodSpec.methodBuilder("annotationType")
        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
        .returns(ClassName.get(java.lang.Class.class))
        .addStatement("return $L.class", aClassName)
        .build();

    TypeSpec.Builder annotationImplType = TypeSpec.classBuilder(annotationClass.getSimpleName() + "$$Impl")
        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
        .addSuperinterface(util.getClassName(annotationClass))
        .addMethod(annotationTypeMethod);

    System.out.println("annotation methods " + annotationClass.getMethods().size());
    System.out.println("annotation fields " + annotationClass.getFields().length);
    System.out.println("annotation " + annotationClass.toString());

    for (Method method : annotationClass.getMethods()) {
        TypeName type;
        if (method.getReturnType().isArray()) {
            //important to use the component here as there is no method get(TypeName)
            //we fail to be detected as an array (see ArrayTypeName.get implementation)
            type = ArrayTypeName.of(util.getClassName(method.getReturnType().getComponentType()));
        } else {
            type = TypeName.get(method.getReturnType());
        }
        FieldSpec field = FieldSpec.builder(type, method.getName(), Modifier.PRIVATE).build();
        annotationImplType.addField(field);

        MethodSpec setterMethod = createSetterMethod(type, method.getName());
        annotationImplType.addMethod(setterMethod);
        MethodSpec getterMethod = createGetterMethod(type, method.getName());
        annotationImplType.addMethod(getterMethod);
    }

    return JavaFile.builder(targetPackageName, annotationImplType.build()).build();
}