private static TypeName bestGuess(String type) { switch (type) { case "void": return TypeName.VOID; case "boolean": return TypeName.BOOLEAN; case "byte": return TypeName.BYTE; case "char": return TypeName.CHAR; case "double": return TypeName.DOUBLE; case "float": return TypeName.FLOAT; case "int": return TypeName.INT; case "long": return TypeName.LONG; case "short": return TypeName.SHORT; default: int left = type.indexOf('<'); if (left != -1) { ClassName typeClassName = ClassName.bestGuess(type.substring(0, left)); List<TypeName> typeArguments = new ArrayList<>(); do { typeArguments.add(WildcardTypeName.subtypeOf(Object.class)); left = type.indexOf('<', left + 1); } while (left != -1); return ParameterizedTypeName.get(typeClassName, typeArguments.toArray(new TypeName[typeArguments.size()])); } return ClassName.bestGuess(type); } }
private List<MethodSpec> generateConstructors() { ParameterizedTypeName classOfTranscodeType = ParameterizedTypeName.get(ClassName.get(Class.class), transcodeTypeName); TypeName wildcardOfObject = WildcardTypeName.subtypeOf(Object.class); ParameterizedTypeName requestBuilderOfWildcardOfObject = ParameterizedTypeName.get(ClassName.get(requestBuilderType), wildcardOfObject); MethodSpec firstConstructor = MethodSpec.constructorBuilder() .addParameter(classOfTranscodeType, "transcodeClass") .addParameter(requestBuilderOfWildcardOfObject, "other") .addStatement("super($N, $N)", "transcodeClass", "other") .build(); ClassName glide = ClassName.get("com.bumptech.glide", "Glide"); ClassName requestManager = ClassName.get("com.bumptech.glide", "RequestManager"); MethodSpec secondConstructor = MethodSpec.constructorBuilder() .addParameter(glide, "glide") .addParameter(requestManager, "requestManager") .addParameter(classOfTranscodeType, "transcodeClass") .addStatement("super($N, $N ,$N)", "glide", "requestManager", "transcodeClass") .build(); return ImmutableList.of(firstConstructor, secondConstructor); }
ReceiverGenerator generateUnregisterMethod() { MethodSpec.Builder unregisterMB = MethodSpec.methodBuilder("unregisterReceiver"); // Generates cosumers waiting Future for success handler unregistration unregisterMB.addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addStatement("return $T.all($N.stream().map((consumer) -> {" + "$T future = $T.future();" + "consumer.unregister(future);" + "return future;" + "}).collect($T.toList()))", CompositeFuture.class, consumersField, ParameterizedTypeName.get(ClassName.get(Future.class), TypeName.get(Void.class)), TypeName.get(Future.class), TypeName.get(Collectors.class) ) .returns(ParameterizedTypeName.get(ClassName.get(Future.class), WildcardTypeName.subtypeOf(Object.class))); tsb.addMethod(unregisterMB.build()); return this; }
private MethodSpec createIsJsObject() { CodeBlock.Builder builder = CodeBlock.builder(); builder.addStatement("$1T jsType = type.getAnnotation($1T.class)", ClassNames.JSINTEROP_JSTYPE); Stream.of( "jsType == null", "!jsType.isNative()", "!JsPackage.GLOBAL.equals(jsType.namespace())", "!\"Object\".equals(jsType.name())") .forEachOrdered(statement -> builder .beginControlFlow("if (" + statement + ")") .addStatement("return false") .endControlFlow()); builder.addStatement("return true"); return MethodSpec.methodBuilder("isJsObject") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addAnnotation(ClassNames.GWT_INCOMPATIBLE) .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class)), "type") .returns(Boolean.TYPE) .addCode(builder.build()) .build(); }
private MethodSpec builderCopyMethodForList() { TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel() .getVariable().getVariableType()); ClassName valueParameter = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape()); ClassName builderForParameter = valueParameter.nestedClass("Builder"); TypeName parameterType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, WildcardTypeName.subtypeOf(builderForParameter)); CodeBlock code = CodeBlock.builder() .beginControlFlow("if ($N == null)", memberParamName()) .addStatement("return null") .endControlFlow() .addStatement("return $N($N.entrySet().stream().collect(toMap($T::getKey, e -> e.getValue().build())))", serviceModelCopiers.copyMethodName(), memberParamName(), Map.Entry.class) .build(); return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName()) .addModifiers(Modifier.STATIC) .addParameter(parameterType, memberParamName()) .returns(typeProvider.fieldType(memberModel)) .addCode(code) .build(); }
private MethodSpec builderCopyMethodForMap() { ClassName listParameter = poetExtensions.getModelClass(memberModel.getListModel().getListMemberModel().getC2jShape()); ClassName builderForParameter = listParameter.nestedClass("Builder"); TypeName parameterType = ParameterizedTypeName.get(ClassName.get(Collection.class), WildcardTypeName.subtypeOf(builderForParameter)); CodeBlock code = CodeBlock.builder() .beginControlFlow("if ($N == null)", memberParamName()) .addStatement("return null") .endControlFlow() .addStatement("return $N($N.stream().map($T::$N).collect(toList()))", serviceModelCopiers.copyMethodName(), memberParamName(), builderForParameter, "build") .build(); return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName()) .addModifiers(Modifier.STATIC) .addParameter(parameterType, memberParamName()) .returns(typeProvider.fieldType(memberModel)) .addCode(code) .build(); }
private void generateConstructor(TypeSpec.Builder classBuilder) { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.get(targetType), PocketBusConst.VAR_TARGET); if (parentAdapter != null) { builder.addStatement("super($N)", PocketBusConst.VAR_TARGET); } builder.addStatement("this.$N = new $T($N)", PocketBusConst.VAR_TARGET_REF, getWeakReferenceType(), PocketBusConst.VAR_TARGET) .addStatement("$T $N = new $T()", LIST_TYPE, PocketBusConst.VAR_SUBSCRIPTIONS, ParameterizedTypeName.get(ClassName.get(ArrayList.class), ParameterizedTypeName.get(ClassName.get(Subscription.class), WildcardTypeName.subtypeOf(TypeName.OBJECT)))); if (parentAdapter != null) { builder.addStatement("$N.addAll(super.$L())", PocketBusConst.VAR_SUBSCRIPTIONS, PocketBusConst.METHOD_GET_SUBSCRIPTIONS); } for (SubscriptionMethod method : methods) { builder.addStatement("$N.add($N)", PocketBusConst.VAR_SUBSCRIPTIONS, PocketBusConst.VAR_SUBSCRIPTION + method.getIndex()); } builder.addStatement("this.$N = $T.unmodifiableList($N)", PocketBusConst.VAR_SUBSCRIPTIONS, ClassName.get(Collections.class), PocketBusConst.VAR_SUBSCRIPTIONS); classBuilder.addMethod(builder.build()); }
/** * Returns true if the given type can be bound to some type. Note: this should * not be used with raw type of generic type. */ public static boolean isBindable(TypeName typeName) { if (typeName instanceof ParameterizedTypeName) { for (TypeName t : ((ParameterizedTypeName) typeName).typeArguments) { if (!isBindable(t)) { return false; } } return true; } else if (typeName instanceof ClassName) { return true; } else if (typeName instanceof WildcardTypeName) { return true; } else return typeName.isPrimitive(); }
public void generate() { MethodSpec.Builder addHandlerMethod = MethodSpec.methodBuilder("addHandler") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterizedTypeName.get(ClassName.get(IsPresenter.class), WildcardTypeName.subtypeOf(Object.class), WildcardTypeName.subtypeOf(Object.class)), "presenter") .returns(ClassName.get(PresenterRegistration.class)); // TODO implementing addHandler feature ... // // List of already created EventHandler used to avoid a second create ... // List<ClassNameModel> listOfEventHandlersToCreate = this.createListOfEventHandlersToCreate(); // listOfEventHandlersToCreate.forEach(handlerClassName -> this.addHandlerToMetaList(loadEventHandlerMethod, // handlerClassName)); addHandlerMethod.addStatement("return null"); typeSpec.addMethod(addHandlerMethod.build()); }
private void appendTypes(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Resource.class)); specTypes = createMapWithInitializer("types", LinkedHashMap.class, ClassName.get(String.class), classTypeName) .addModifiers(Modifier.FINAL) .build(); builder.addField(specTypes); // Getter builder.addMethod(createGetterImpl(specTypes, "getTypes").build()); }
private void appendModels(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class)); TypeName helperTypeName = ParameterizedTypeName.get(ClassName.get(ModelHelper.class), WildcardTypeName.subtypeOf(Object.class)); specModels = createMapWithInitializer("models", LinkedHashMap.class, classTypeName, helperTypeName).addModifiers(Modifier.FINAL).build(); builder.addField(specModels); // Getter builder.addMethod(createGetterImpl(specModels, "getModels").build()); }
@Test public void testAdderAll() throws Exception { BuildableRDFSProperty loadCap = getPropertyFromModel("http://example.de/ont#load_capacity"); assertNotNull(loadCap); MethodSpec loadCapSpec = loadCap.buildAdderAll(declaringClass, generationConfig); // Test signature: assertEquals("addAllMaximumLoadCapacities", loadCapSpec.name); assertTrue(loadCapSpec.modifiers.contains(Modifier.PUBLIC)); assertEquals(1, loadCapSpec.parameters.size()); ClassName setClass = ClassName.get("java.util", "Set"); assertEquals(ParameterizedTypeName.get(setClass, WildcardTypeName.subtypeOf(ClassName.get(Float.class))), loadCapSpec.parameters.get(0).type); // Test JavaDoc: assertNotNull(loadCapSpec.javadoc); assertTrue(loadCapSpec.javadoc.toString().startsWith("Ladung in Tonnen")); // Test annotation: assertEquals(0, loadCapSpec.annotations.size()); }
@Test public void testRemoverAll() throws Exception { BuildableRDFSProperty loadCap = getPropertyFromModel("http://example.de/ont#load_capacity"); assertNotNull(loadCap); MethodSpec loadCapSpec = loadCap.buildRemoverAll(declaringClass, generationConfig); // Test signature: assertEquals("removeAllMaximumLoadCapacities", loadCapSpec.name); assertTrue(loadCapSpec.modifiers.contains(Modifier.PUBLIC)); assertEquals(1, loadCapSpec.parameters.size()); ClassName setClass = ClassName.get("java.util", "Set"); assertEquals(ParameterizedTypeName.get(setClass, WildcardTypeName.subtypeOf(ClassName.get(Float.class))), loadCapSpec.parameters.get(0).type); // Test JavaDoc: assertNotNull(loadCapSpec.javadoc); assertTrue(loadCapSpec.javadoc.toString().startsWith("Ladung in Tonnen")); // Test annotation: assertEquals(0, loadCapSpec.annotations.size()); }
private static String simpleName(TypeName typeName) { if (typeName instanceof ClassName) { return UPPER_CAMEL.to(LOWER_CAMEL, ((ClassName) typeName).simpleName()); } else if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName; return UPPER_CAMEL.to(LOWER_CAMEL, parameterizedTypeName.rawType.simpleName()) + (parameterizedTypeName.typeArguments.isEmpty() ? "" : "__") + simpleName(parameterizedTypeName.typeArguments); } else if (typeName instanceof ArrayTypeName) { return "array__" + simpleName(((ArrayTypeName) typeName).componentType); } else if (typeName instanceof WildcardTypeName) { WildcardTypeName wildcardTypeName = (WildcardTypeName) typeName; return "wildcard__" + simpleName(ImmutableList.<TypeName>builder().addAll(wildcardTypeName.lowerBounds) .addAll(wildcardTypeName.upperBounds) .build()); } else if (typeName instanceof TypeVariableName) { TypeVariableName variable = (TypeVariableName) typeName; return variable.name + (variable.bounds.isEmpty() ? "" : "__") + simpleName(variable.bounds); } else { return typeName.toString(); } }
private MethodSpec createStartServices() { ClassName memoryServiceConnection = ClassName.get(PACKAGE, "MemoryServiceConnection"); CodeBlock code = CodeBlock.builder() .beginControlFlow("for($T service: $L)", ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Service.class)), FIELD_SERVICES) .addStatement("$T intent = new $T(context, service)", Intent.class, Intent.class) .addStatement("context.startService(intent)") .add("\n") .addStatement("$T connection = new $T()", memoryServiceConnection, memoryServiceConnection) .addStatement("context.bindService(intent, connection, Context.BIND_AUTO_CREATE)") .endControlFlow() .build(); return MethodSpec.methodBuilder("startServices") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(ClassName.get(Context.class), "context") .addCode(code) .build(); }
private MethodSpec collectionCollectionSetter(final Descriptor d, final ExecutableElement field) { String fieldName = fieldName(field); ClassName collectionType = ClassName.get(Collection.class); TypeName itemType = genericArgument(field, 0); WildcardTypeName extendedType = subtypeOf(itemType); MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName) .addModifiers(PUBLIC) .addParameter(ParameterizedTypeName.get(collectionType, extendedType), fieldName) .returns(builderType(d)); collectionNullGuard(setter, field); if (shouldEnforceNonNull(field)) { setter.beginControlFlow("for ($T item : $N)", itemType, fieldName); assertNotNull(setter, "item", fieldName + ": null item"); setter.endControlFlow(); } setter.addStatement("this.$N = new $T($N)", fieldName, collectionImplType(field), fieldName); return setter.addStatement("return this").build(); }
private MethodSpec collectionIterableSetter(final Descriptor d, final ExecutableElement field) { String fieldName = fieldName(field); ClassName iterableType = ClassName.get(Iterable.class); TypeName itemType = genericArgument(field, 0); WildcardTypeName extendedType = subtypeOf(itemType); MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName) .addModifiers(PUBLIC) .addParameter(ParameterizedTypeName.get(iterableType, extendedType), fieldName) .returns(builderType(d)); collectionNullGuard(setter, field); ClassName collectionType = ClassName.get(Collection.class); setter.beginControlFlow("if ($N instanceof $T)", fieldName, collectionType) .addStatement("return $N(($T<$T>) $N)", fieldName, collectionType, extendedType, fieldName) .endControlFlow(); setter.addStatement("return $N($N.iterator())", fieldName, fieldName); return setter.build(); }
private MethodSpec collectionIteratorSetter(final Descriptor d, final ExecutableElement field) { String fieldName = fieldName(field); ClassName iteratorType = ClassName.get(Iterator.class); TypeName itemType = genericArgument(field, 0); WildcardTypeName extendedType = subtypeOf(itemType); MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName) .addModifiers(PUBLIC) .addParameter(ParameterizedTypeName.get(iteratorType, extendedType), fieldName) .returns(builderType(d)); collectionNullGuard(setter, field); setter.addStatement("this.$N = new $T()", fieldName, collectionImplType(field)) .beginControlFlow("while ($N.hasNext())", fieldName) .addStatement("$T item = $N.next()", itemType, fieldName); if (shouldEnforceNonNull(field)) { assertNotNull(setter, "item", fieldName + ": null item"); } setter.addStatement("this.$N.add(item)", fieldName) .endControlFlow(); return setter.addStatement("return this").build(); }
private MethodSpec generateGetExcludedModuleClasses(Set<String> excludedClassNames) { TypeName wildCardOfObject = WildcardTypeName.subtypeOf(Object.class); ParameterizedTypeName classOfWildcardOfObjet = ParameterizedTypeName.get(ClassName.get(Class.class), wildCardOfObject); ParameterizedTypeName setOfClassOfWildcardOfObject = ParameterizedTypeName.get(ClassName.get(Set.class), classOfWildcardOfObjet); ParameterizedTypeName hashSetOfClassOfWildcardOfObject = ParameterizedTypeName.get(ClassName.get(HashSet.class), classOfWildcardOfObjet); MethodSpec.Builder builder = MethodSpec.methodBuilder("getExcludedModuleClasses") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(setOfClassOfWildcardOfObject); if (excludedClassNames.isEmpty()) { builder.addStatement("return $T.emptySet()", Collections.class); } else { builder.addStatement( "$T excludedClasses = new $T()", setOfClassOfWildcardOfObject, hashSetOfClassOfWildcardOfObject); for (String excludedClassName : excludedClassNames) { // TODO: Remove this when we no longer support manifest parsing. // Using a Literal ($L) instead of a type ($T) to get a fully qualified import that allows // us to suppress deprecation warnings. Aimed at deprecated GlideModules. builder.addStatement("excludedClasses.add($L.class)", excludedClassName); } builder.addStatement("return excludedClasses"); } return builder.build(); }
private List<MethodSpec> generateConstructors() { ParameterizedTypeName classOfTranscodeType = ParameterizedTypeName.get(ClassName.get(Class.class), transcodeTypeName); TypeName wildcardOfObject = WildcardTypeName.subtypeOf(Object.class); ParameterizedTypeName requestBuilderOfWildcardOfObject = ParameterizedTypeName.get(ClassName.get(requestBuilderType), wildcardOfObject); MethodSpec firstConstructor = MethodSpec.constructorBuilder() .addParameter(classOfTranscodeType, "transcodeClass") .addParameter(requestBuilderOfWildcardOfObject, "other") .addStatement("super($N, $N)", "transcodeClass", "other") .build(); ClassName context = ClassName.get("android.content", "Context"); ClassName glide = ClassName.get("com.bumptech.glide", "Glide"); ClassName requestManager = ClassName.get("com.bumptech.glide", "RequestManager"); MethodSpec secondConstructor = MethodSpec.constructorBuilder() .addParameter(glide, "glide") .addParameter(requestManager, "requestManager") .addParameter(classOfTranscodeType, "transcodeClass") .addParameter(context, "context") .addStatement( "super($N, $N ,$N, $N)", "glide", "requestManager", "transcodeClass", "context") .build(); return ImmutableList.of(firstConstructor, secondConstructor); }
public static JavaFile statement(Domain ontology) { ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + MARKER_MDC); ClassName markerName = MarkerGenerator.getName(ontology); TypeName wildcard = WildcardTypeName.subtypeOf(DomainMarker.class); TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard); ParameterSpec type = ParameterSpec.builder(classOfAny, "type").build(); return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name) .superclass(ParameterizedTypeName.get( ClassName.get(DomainMdc.class), markerName)) .addModifiers(Modifier.PUBLIC) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addStatement("super($T.QUALIFIER)", markerName) .build() ) .addMethod(MethodSpec.methodBuilder("createMarker") .addModifiers(Modifier.PUBLIC) .addStatement("return new $T()", markerName) .returns(markerName) .build() ) .addMethod(MethodSpec.methodBuilder("supports") .addModifiers(Modifier.PUBLIC) .addParameter(type) .addStatement("return $T.class == $N", markerName, type) .returns(boolean.class) .build() ) .build()) .build(); }
@Override protected TypeSpec generate() { TypeSpec.Builder builder = TypeSpec.classBuilder("BuilderUtil") .addModifiers(Modifier.PUBLIC) .addField(FieldSpec.builder( ParameterizedTypeName.get(ClassName.get(HashMap.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Activity.class)), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(baseActivityBuilder))) ), "sBuilderMap") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("new $T<>()", HashMap.class) .build()); MethodSpec createBuilder = buildCreateBuilder(); builder.addMethod(createBuilder) .addMethod(buildCreateBuilderWithIntent()) .addMethod(buildSmallCreate(createBuilder)); CodeBlock.Builder mapIniter = CodeBlock.builder(); for (TypeElement element : activityList) { addBuilderToMap(mapIniter, element); builder.addMethod(buildCreateHelper(element)); } builder.addStaticBlock(mapIniter.build()); return builder.build(); }
private MethodSpec buildCreateBuilder() { return MethodSpec.methodBuilder("createBuilder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariable(TypeVariableName.get("A", ClassName.get(activity))) .returns(ParameterizedTypeName.get(ClassName.get(baseActivityBuilder), WildcardTypeName.subtypeOf(ClassName.get(baseActivityBuilder)), TypeVariableName.get("A"))) .addParameter(TypeVariableName.get("A"), "activity") .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(activity))), "clazz") .addStatement("return $T.create($L, $L)", ClassName.get(baseActivityBuilder), "activity", "clazz") .build(); }
private MethodSpec buildCreateBuilderWithIntent() { return MethodSpec.methodBuilder("createBuilder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariable(TypeVariableName.get("A", ClassName.get(activity))) .returns(ParameterizedTypeName.get(ClassName.get(baseActivityBuilder), WildcardTypeName.subtypeOf(ClassName.get(baseActivityBuilder)), TypeVariableName.get("A"))) .addParameter(TypeVariableName.get("A"), "activity") .addParameter(ClassName.get(Intent.class), "intent") .addStatement("return $T.create($L, $L)", ClassName.get(baseActivityBuilder), "activity", "intent") .build(); }
private MethodSpec buildSmallCreate(MethodSpec createBuilder) { MethodSpec.Builder builder = MethodSpec.methodBuilder("smallCreate") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariable(TypeVariableName.get("A", ClassName.get(activity))) .addTypeVariable(TypeVariableName.get("T", ParameterizedTypeName.get(ClassName.get(baseActivityBuilder), TypeVariableName.get("T"), TypeVariableName.get("A")))) .returns(TypeVariableName.get("T")) .addParameter(TypeVariableName.get("A"), "activity") .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(activity))), "clazz"); builder.beginControlFlow("if ($L.containsKey($L))", "sBuilderMap", "clazz") .beginControlFlow("try") .addStatement("return (T) $L.get($L).getMethod($S, $T.class).invoke(null,$L)", "sBuilderMap", "clazz", "create", ClassName.get(activity), "activity") .endControlFlow() // try .beginControlFlow("catch ($T e)", ClassName.get(NoSuchMethodException.class)) .addStatement("e.printStackTrace()") .endControlFlow() .beginControlFlow("catch ($T e)", ClassName.get(IllegalAccessException.class)) .addStatement("e.printStackTrace()") .endControlFlow() .beginControlFlow("catch ($T e)", ClassName.get(InvocationTargetException.class)) .addStatement("e.printStackTrace()") .endControlFlow() .endControlFlow() // if .addStatement("return (T) $N($L,$L)", createBuilder, "activity", "clazz"); return builder.build(); }
private static TypeName withWildCardTypeParameters(OutputValue value) { if (!value.hasTypeVariables()) { return value.outputClass(); } TypeName[] wildCards = new TypeName[Iterables.sizeOf(value.typeVariables())]; Arrays.fill(wildCards, WildcardTypeName.subtypeOf(TypeName.OBJECT)); return ParameterizedTypeName.get(value.outputClass(), wildCards); }
ReceiverGenerator generateInitializing() { tsb = TypeSpec.classBuilder(MessageFormat.format("{0}{1}", interfaceElement.getSimpleName(), VXRIFA_RECEIVER_SUFFIX)).addModifiers(Modifier.PUBLIC); tsb.addSuperinterface(ParameterizedTypeName.get(ClassName.get(VxRifaReceiver.class), TypeName.get(interfaceElement.asType()))); vertxField = FieldSpec.builder(io.vertx.core.Vertx.class, "vertx", Modifier.PRIVATE, Modifier.FINAL).build(); tsb.addField(vertxField); eventBusAddressField = FieldSpec.builder(java.lang.String.class, "eventBusAddress", Modifier.PRIVATE, Modifier.FINAL).build(); tsb.addField(eventBusAddressField); consumersField = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class), ParameterizedTypeName.get(ClassName.get(MessageConsumer.class), WildcardTypeName.subtypeOf(Object.class))), "consumers", Modifier.PRIVATE) .build(); tsb.addField(consumersField); tsb.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(io.vertx.core.Vertx.class, vertxField.name) .addStatement("this.$N = $N", vertxField, vertxField) .addStatement("this.$N = $S", eventBusAddressField, interfaceElement.getQualifiedName().toString()) .build() ); tsb.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(io.vertx.core.Vertx.class, vertxField.name) .addParameter(java.lang.String.class, eventBusAddressField.name) .addStatement("this.$N = $N", vertxField, vertxField) .addStatement("this.$N = $N", eventBusAddressField, eventBusAddressField) .build() ); return this; }
private static CodeBlock makeType(TypeName type) { CodeBlock.Builder block = CodeBlock.builder(); if (type instanceof ParameterizedTypeName) { ParameterizedTypeName pType = (ParameterizedTypeName) type; block.add("$T.newParameterizedType($T.class", Types.class, pType.rawType); for (TypeName typeArg : pType.typeArguments) { if (typeArg instanceof ParameterizedTypeName) { block.add(", $L", makeType(typeArg)); } else if (typeArg instanceof WildcardTypeName) { WildcardTypeName wildcard = (WildcardTypeName) typeArg; TypeName target; String method; if (wildcard.lowerBounds.size() == 1) { target = wildcard.lowerBounds.get(0); method = "supertypeOf"; } else if (wildcard.upperBounds.size() == 1) { target = wildcard.upperBounds.get(0); method = "subtypeOf"; } else { throw new IllegalArgumentException( "Unrepresentable wildcard type. Cannot have more than one bound: " + wildcard); } block.add(", $T.$L($T.class)", Types.class, method, target); } else { block.add(", $T.class", typeArg); } } block.add(")"); } else { block.add("$T.class", type); } return block.build(); }
public static TypeName bestGuess(String type) { switch (type) { case "void": return TypeName.VOID; case "boolean": return TypeName.BOOLEAN; case "byte": return TypeName.BYTE; case "char": return TypeName.CHAR; case "double": return TypeName.DOUBLE; case "float": return TypeName.FLOAT; case "int": return TypeName.INT; case "long": return TypeName.LONG; case "short": return TypeName.SHORT; default: int left = type.indexOf('<'); if (left != -1) { ClassName typeClassName = ClassName.bestGuess(type.substring(0, left)); List<TypeName> typeArguments = new ArrayList<>(); do { typeArguments.add(WildcardTypeName.subtypeOf(Object.class)); left = type.indexOf('<', left + 1); } while (left != -1); return ParameterizedTypeName.get(typeClassName, typeArguments.toArray(new TypeName[typeArguments.size()])); } return ClassName.bestGuess(type); } }
/** * @param type * @return */ public static TypeName bestGuessDeep(String type) { switch (type) { case "void": return TypeName.VOID; case "boolean": return TypeName.BOOLEAN; case "byte": return TypeName.BYTE; case "char": return TypeName.CHAR; case "double": return TypeName.DOUBLE; case "float": return TypeName.FLOAT; case "int": return TypeName.INT; case "long": return TypeName.LONG; case "short": return TypeName.SHORT; default: int left = type.indexOf('<'); int right = type.indexOf('>'); if (-1 != left && -1 != right) { ClassName typeClassName = ClassName.bestGuess(type.substring(0, left)); List<TypeName> typeArguments = new ArrayList<>(); do { typeArguments.add(WildcardTypeName.subtypeOf(bestGuess(type.substring(left + 1, right)))); left = type.indexOf('<', left + 1); right = type.indexOf('>', right - 1); } while (left != -1); return ParameterizedTypeName.get(typeClassName, typeArguments.toArray(new TypeName[typeArguments.size()])); } return ClassName.bestGuess(type); } }
private MethodSpec serializableBuilderClass() { return MethodSpec.methodBuilder("serializableBuilderClass") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(modelBuilderSpecs.builderInterfaceName()))) .addStatement("return $T.class", modelBuilderSpecs.builderImplName()) .build(); }
public TypeName parameterType(MemberModel memberModel) { if (memberModel.isList()) { ListModel listModel = memberModel.getListModel(); MemberModel elementModel = listModel.getListMemberModel(); TypeName listElementType = parameterType(elementModel); if (elementModel.isList()) { listElementType = WildcardTypeName.subtypeOf(listElementType); } return ParameterizedTypeName.get(ClassName.get(Collection.class), listElementType); } if (memberModel.isMap()) { MapModel mapModel = memberModel.getMapModel(); TypeName keyType; if (mapModel.getKeyModel().isSimple()) { keyType = getTypeNameForSimpleType(mapModel.getKeyModel().getVariable().getVariableType()); } else { keyType = parameterType(mapModel.getKeyModel()); } TypeName valueType = parameterType(mapModel.getValueModel()); if (mapModel.getValueModel().isList()) { valueType = WildcardTypeName.subtypeOf(valueType); } return ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType); } return fieldType(memberModel); }
public TypeName mapEntryType(MapModel mapModel) { TypeName keyType; if (mapModel.getKeyModel().isSimple()) { keyType = getTypeNameForSimpleType(mapModel.getKeyModel().getVariable().getVariableType()); } else { keyType = parameterType(mapModel.getKeyModel()); } TypeName valueType = parameterType(mapModel.getValueModel()); if (mapModel.getValueModel().isList()) { valueType = WildcardTypeName.subtypeOf(valueType); } return ParameterizedTypeName.get(ClassName.get(Map.Entry.class), keyType, valueType); }
@Override public void updatePluginProviderInterface(TypeSpec.Builder serviceInterface, UserMarkerAnnotation annotation) { TypeName returnType = annotation.getServiceInterfaceTypeName(); MethodSpec deserializeWithoutConfig = Util.publicAbstractMethod("deserialize", returnType) .build(); MethodSpec deserializeWithConfig = Util.publicAbstractMethod("deserialize", returnType) .addParameter(JsonParser.class, "config") .build(); TypeName configType = ParameterizedTypeName.get(ClassName.get(TypeReference.class), WildcardTypeName.subtypeOf(Object.class)); MethodSpec getConfigTypeReference = Util.publicAbstractMethod("getConfigTypeReference", configType).build(); serviceInterface.addMethod(deserializeWithoutConfig); serviceInterface.addMethod(deserializeWithConfig); serviceInterface.addMethod(getConfigTypeReference); }
private void generate(String destinationDir) throws IOException { String typesPackageName = "org.web3j.abi.datatypes"; String autoGeneratedTypesPackageName = typesPackageName + ".generated"; MethodSpec.Builder builder = MethodSpec.methodBuilder("getType") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(String.class, TYPE) .returns( ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class)) ) .beginControlFlow("switch (type)"); builder = addTypes(builder, typesPackageName); builder = addGeneratedTypes(builder, autoGeneratedTypesPackageName); builder = builder.addStatement("default:\nthrow new $T($S)", UnsupportedOperationException.class, "Unsupported type encountered"); builder.endControlFlow(); MethodSpec methodSpec = builder.build(); MethodSpec constructorSpec = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); TypeSpec typeSpec = TypeSpec .classBuilder("AbiTypes") .addJavadoc(buildWarning(AbiTypesMapperGenerator.class)) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(constructorSpec) .addMethod(methodSpec) .build(); write(autoGeneratedTypesPackageName, typeSpec, destinationDir); }
/** * Reference -> https://github.com/JakeWharton/butterknife/blob/master/butterknife-compiler/src/main/java/butterknife/compiler/BindingClass.java * @param type * @return */ public static TypeName bestGuess(String type) { switch (type) { case "void": return TypeName.VOID; case "boolean": return TypeName.BOOLEAN; case "byte": return TypeName.BYTE; case "char": return TypeName.CHAR; case "double": return TypeName.DOUBLE; case "float": return TypeName.FLOAT; case "int": return TypeName.INT; case "long": return TypeName.LONG; case "short": return TypeName.SHORT; default: int left = type.indexOf('<'); if (left != -1) { ClassName typeClassName = ClassName.bestGuess(type.substring(0, left)); List<TypeName> typeArguments = new ArrayList<>(); do { typeArguments.add(WildcardTypeName.subtypeOf(Object.class)); left = type.indexOf('<', left + 1); } while (left != -1); return ParameterizedTypeName.get(typeClassName, typeArguments.toArray(new TypeName[typeArguments.size()])); } return ClassName.bestGuess(type); } }