Java Code Examples for javax.lang.model.type.ExecutableType#getParameterTypes()

The following examples show how to use javax.lang.model.type.ExecutableType#getParameterTypes() . 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: AbstractTestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
private List<VariableTree> generateParamVariables(
                                        WorkingCopy workingCopy,
                                        ExecutableType srcMethod,
                                        String[] varNames) {
    TreeMaker maker = workingCopy.getTreeMaker();
    List<? extends TypeMirror> params = srcMethod.getParameterTypes();
    if ((params == null) || params.isEmpty()) {
        return Collections.<VariableTree>emptyList();
    }

    Set<Modifier> noModifiers = Collections.<Modifier>emptySet();
    List<VariableTree> paramVariables = new ArrayList<VariableTree>(params.size());
    int index = 0;
    for (TypeMirror param : params) {
        if (param.getKind() == TypeKind.TYPEVAR){
            param = getSuperType(workingCopy, param);
        }
        paramVariables.add(
                maker.Variable(maker.Modifiers(noModifiers),
                               varNames[index++],
                               maker.Type(param),
                               getDefaultValue(maker, param)));
    }
    return paramVariables;
}
 
Example 2
Source File: MethodSpec.java    From javapoet with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new method spec builder that overrides {@code method} as a member of {@code
 * enclosing}. This will resolve type parameters: for example overriding {@link
 * Comparable#compareTo} in a type that implements {@code Comparable<Movie>}, the {@code T}
 * parameter will be resolved to {@code Movie}.
 *
 * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
 * throws declarations. An {@link Override} annotation will be added.
 *
 * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
 * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
 */
public static Builder overriding(
    ExecutableElement method, DeclaredType enclosing, Types types) {
  ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method);
  List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
  List<? extends TypeMirror> resolvedThrownTypes = executableType.getThrownTypes();
  TypeMirror resolvedReturnType = executableType.getReturnType();

  Builder builder = overriding(method);
  builder.returns(TypeName.get(resolvedReturnType));
  for (int i = 0, size = builder.parameters.size(); i < size; i++) {
    ParameterSpec parameter = builder.parameters.get(i);
    TypeName type = TypeName.get(resolvedParameterTypes.get(i));
    builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build());
  }
  builder.exceptions.clear();
  for (int i = 0, size = resolvedThrownTypes.size(); i < size; i++) {
    builder.addException(TypeName.get(resolvedThrownTypes.get(i)));
  }

  return builder;
}
 
Example 3
Source File: MethodSpec.java    From JReFrameworker with MIT License 6 votes vote down vote up
/**
 * Returns a new method spec builder that overrides {@code method} as a member of {@code
 * enclosing}. This will resolve type parameters: for example overriding {@link
 * Comparable#compareTo} in a type that implements {@code Comparable<Movie>}, the {@code T}
 * parameter will be resolved to {@code Movie}.
 *
 * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
 * throws declarations. An {@link Override} annotation will be added.
 *
 * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
 * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
 */
public static Builder overriding(
    ExecutableElement method, DeclaredType enclosing, Types types) {
  ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method);
  List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
  TypeMirror resolvedReturnType = executableType.getReturnType();

  Builder builder = overriding(method);
  builder.returns(TypeName.get(resolvedReturnType));
  for (int i = 0, size = builder.parameters.size(); i < size; i++) {
    ParameterSpec parameter = builder.parameters.get(i);
    TypeName type = TypeName.get(resolvedParameterTypes.get(i));
    builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build());
  }

  return builder;
}
 
Example 4
Source File: MoreTypes.java    From auto-parcel with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves a {@link VariableElement} parameter to a method or constructor based on the given
 * container, or a member of a class. For parameters to a method or constructor, the variable's
 * enclosing element must be a supertype of the container type. For example, given a
 * {@code container} of type {@code Set<String>}, and a variable corresponding to the {@code E e}
 * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}.
 */
public static TypeMirror asMemberOf(Types types, DeclaredType container,
                                    VariableElement variable) {
    if (variable.getKind().equals(ElementKind.PARAMETER)) {
        ExecutableElement methodOrConstructor =
                MoreElements.asExecutable(variable.getEnclosingElement());
        ExecutableType resolvedMethodOrConstructor = MoreTypes.asExecutable(
                types.asMemberOf(container, methodOrConstructor));
        List<? extends VariableElement> parameters = methodOrConstructor.getParameters();
        List<? extends TypeMirror> parameterTypes =
                resolvedMethodOrConstructor.getParameterTypes();
        checkState(parameters.size() == parameterTypes.size());
        for (int i = 0; i < parameters.size(); i++) {
            // We need to capture the parameter type of the variable we're concerned about,
            // for later printing.  This is the only way to do it since we can't use
            // types.asMemberOf on variables of methods.
            if (parameters.get(i).equals(variable)) {
                return parameterTypes.get(i);
            }
        }
        throw new IllegalStateException("Could not find variable: " + variable);
    } else {
        return types.asMemberOf(container, variable);
    }
}
 
Example 5
Source File: DecoratorInterceptorLogic.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Triple<VariableElement, TypeMirror, Void> getDelegate(
        ExecutableElement method, TypeElement decorator )
{
    List<? extends VariableElement> parameters = method.getParameters();
    int index =0;
    VariableElement delegate = null;
    for (VariableElement variableElement : parameters) {
        if ( AnnotationObjectProvider.hasAnnotation(variableElement, 
                DELEGATE_ANNOTATION, getModel().getHelper()))
        {
            delegate = variableElement;
            break;
        }
        index ++;
    }
    if ( delegate == null ){
        return null;
    }
    ExecutableType methodType = (ExecutableType)getCompilationController().
        getTypes().asMemberOf((DeclaredType)decorator.asType(), method );
    List<? extends TypeMirror> parameterTypes = methodType.getParameterTypes();
    TypeMirror typeMirror = parameterTypes.get(index);
    return new Triple<VariableElement, TypeMirror, Void>(delegate, typeMirror, null);
}
 
Example 6
Source File: MoreTypes.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves a {@link VariableElement} parameter to a method or constructor based on the given
 * container, or a member of a class. For parameters to a method or constructor, the variable's
 * enclosing element must be a supertype of the container type. For example, given a
 * {@code container} of type {@code Set<String>}, and a variable corresponding to the {@code E e}
 * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}.
 */
public static TypeMirror asMemberOf(Types types, DeclaredType container,
    VariableElement variable) {
  if (variable.getKind().equals(ElementKind.PARAMETER)) {
    ExecutableElement methodOrConstructor =
        MoreElements.asExecutable(variable.getEnclosingElement());
    ExecutableType resolvedMethodOrConstructor =
        MoreTypes.asExecutable(types.asMemberOf(container, methodOrConstructor));
    List<? extends VariableElement> parameters = methodOrConstructor.getParameters();
    List<? extends TypeMirror> parameterTypes = resolvedMethodOrConstructor.getParameterTypes();
    checkState(parameters.size() == parameterTypes.size());
    for (int i = 0; i < parameters.size(); i++) {
      // We need to capture the parameter type of the variable we're concerned about,
      // for later printing.  This is the only way to do it since we can't use
      // types.asMemberOf on variables of methods.
      if (parameters.get(i).equals(variable)) {
        return parameterTypes.get(i);
      }
    }
    throw new IllegalStateException("Could not find variable: " + variable);
  } else {
    return types.asMemberOf(container, variable);
  }
}
 
Example 7
Source File: DelegateMethodAnalyzer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkDelegateType( VariableElement element, int i,
        ExecutableElement method, TypeElement parent,
        CdiAnalysisResult result  )
{
    ExecutableType methodType = (ExecutableType) result.getInfo().getTypes()
            .asMemberOf((DeclaredType) parent.asType(), method);
    List<? extends TypeMirror> parameterTypes = methodType
            .getParameterTypes();
    TypeMirror parameterType = parameterTypes.get(i);
    Collection<TypeMirror> decoratedTypes = DelegateFieldAnalizer
            .getDecoratedTypes(parent, result.getInfo());
    for (TypeMirror decoratedType : decoratedTypes) {
        if (!result.getInfo().getTypes().isSubtype(parameterType, decoratedType)) {
            result.addError(element,  NbBundle.getMessage(
                            DelegateMethodAnalyzer.class,
                            "ERR_DelegateTypeHasNoDecoratedType")); // NOI18N
            return;
        }
    }
}
 
Example 8
Source File: JavaDocGenerator.java    From vertx-docgen with Apache License 2.0 6 votes vote down vote up
private String toExecutableLink(ExecutableElement elt, String name) {
  TypeElement typeElt = (TypeElement) elt.getEnclosingElement();
  String link = resolveTypeLink(typeElt, null);
  StringBuilder anchor = new StringBuilder("#");
  anchor.append(name).append('-');
  TypeMirror type = elt.asType();
  ExecutableType methodType = (ExecutableType) processingEnv.getTypeUtils().erasure(type);
  List<? extends TypeMirror> parameterTypes = methodType.getParameterTypes();
  for (int i = 0; i < parameterTypes.size(); i++) {
    if (i > 0) {
      anchor.append('-');
    }
    // We need to check whether or not the parameter is annotated. In this case, we must use the unannotated type.
    TypeMirror typeOfParameter = parameterTypes.get(i);
    if (typeOfParameter instanceof Type && ((Type) typeOfParameter).isAnnotated()) {
      anchor.append(((Type) typeOfParameter).unannotatedType().toString());
    } else {
      anchor.append(typeOfParameter.toString());
    }
  }
  anchor.append('-');
  return link + anchor;
}
 
Example 9
Source File: SignatureFactory.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the JVM spec requires a signature to be emitted for this method. See JVMS8
 * 4.7.9.1
 */
private static boolean signatureRequired(ExecutableType type) {
  if (!type.getTypeVariables().isEmpty()) {
    return true;
  }

  if (usesGenerics(type.getReturnType())) {
    return true;
  }

  for (TypeMirror parameterType : type.getParameterTypes()) {
    if (usesGenerics(parameterType)) {
      return true;
    }
  }

  return throwsATypeVar(type);
}
 
Example 10
Source File: JavaEnvironment.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MethodDescriptor from javac internal representation.
 *
 * @param methodType an ExecutableType containing the (inferred) specialization of the method in a
 *     usage location.
 * @param returnType the (inferred) specialized return type.
 * @param declarationMethodElement the method declaration.
 */
MethodDescriptor createMethodDescriptor(
    ExecutableType methodType, Type returnType, ExecutableElement declarationMethodElement) {

  DeclaredTypeDescriptor enclosingTypeDescriptor =
      createDeclaredTypeDescriptor(declarationMethodElement.getEnclosingElement().asType());

  MethodDescriptor declarationMethodDescriptor = null;
  List<? extends TypeMirror> parameterTypes = methodType.getParameterTypes();
  if (isSpecialized(declarationMethodElement, parameterTypes, returnType)) {
    declarationMethodDescriptor = createDeclarationMethodDescriptor(declarationMethodElement);
  }

  TypeDescriptor returnTypeDescriptor =
      applyReturnTypeNullabilityAnnotations(
          createTypeDescriptorWithNullability(
              returnType, declarationMethodElement.getAnnotationMirrors()),
          declarationMethodElement);

  ImmutableList.Builder<TypeDescriptor> parametersBuilder = ImmutableList.builder();
  for (int i = 0; i < parameterTypes.size(); i++) {
    parametersBuilder.add(
        applyParameterNullabilityAnnotations(
            createTypeDescriptorWithNullability(
                parameterTypes.get(i),
                declarationMethodElement.getParameters().get(i).getAnnotationMirrors()),
            declarationMethodElement,
            i));
  }

  // generate type parameters declared in the method.
  return createDeclaredMethodDescriptor(
      enclosingTypeDescriptor.toNullable(),
      declarationMethodElement,
      declarationMethodDescriptor,
      parametersBuilder.build(),
      returnTypeDescriptor);
}
 
Example 11
Source File: TypeUtil.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the descriptor of a constructor or method (JLS 4.3.3).
 */
public String getMethodDescriptor(ExecutableType method) {
  StringBuilder sb = new StringBuilder("(");
  for (TypeMirror t : method.getParameterTypes()) {
    sb.append(getSignatureName(t));
  }
  sb.append(")");
  sb.append(getSignatureName(method.getReturnType()));
  return sb.toString();
}
 
Example 12
Source File: AddConstructor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    if (!TreeUtilities.CLASS_TREE_KINDS.contains(treePath.getLeaf().getKind())) return Collections.emptyList();
    
    Element el = info.getTrees().getElement(treePath);
    
    if (el == null || !el.getKind().isClass()) return Collections.emptyList();
    
    TypeElement clazz = (TypeElement) el;
    TypeMirror superType = clazz.getSuperclass();
    
    if (superType.getKind() != TypeKind.DECLARED) return Collections.emptyList();
    
    TypeElement superClazz = (TypeElement) info.getTypes().asElement(superType);
    DeclaredType targetType = (DeclaredType) clazz.asType();
    Scope classScope = info.getTrees().getScope(treePath);
    List<Fix> result = new ArrayList<Fix>();
    
    for (ExecutableElement constr : ElementFilter.constructorsIn(superClazz.getEnclosedElements())) {
        if (!info.getTrees().isAccessible(classScope, constr, (DeclaredType) superType)) continue;
        
        StringBuilder name = new StringBuilder();
        
        name.append(clazz.getSimpleName()).append("(");
        
        ExecutableType target = (ExecutableType) info.getTypes().asMemberOf(targetType, constr);
        boolean firstParam = true;
        
        for (TypeMirror p : target.getParameterTypes()) {
            if (!firstParam) name.append(", ");
            firstParam = false;
            name.append(info.getTypeUtilities().getTypeName(p));
        }
        
        name.append(")");
        result.add(new FixImpl(info, treePath, constr, StringEscapeUtils.escapeHtml(name.toString())).toEditorFix());
    }
    
    return result;
}
 
Example 13
Source File: HandleDelegate.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static String printSig(ExecutableType method, Name name, JavacTypes types) {
	StringBuilder sb = new StringBuilder();
	sb.append(name.toString()).append("(");
	boolean first = true;
	for (TypeMirror param : method.getParameterTypes()) {
		if (!first) sb.append(", ");
		first = false;
		sb.append(typeBindingToSignature(param, types));
	}
	return sb.append(")").toString();
}
 
Example 14
Source File: MethodSignature.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
static MethodSignature fromExecutableType(String methodName, ExecutableType methodType) {
  checkNotNull(methodType);
  ImmutableList.Builder<Equivalence.Wrapper<TypeMirror>> parameters = ImmutableList.builder();
  ImmutableList.Builder<Equivalence.Wrapper<TypeMirror>> thrownTypes = ImmutableList.builder();
  for (TypeMirror parameter : methodType.getParameterTypes()) {
    parameters.add(MoreTypes.equivalence().wrap(parameter));
  }
  for (TypeMirror thrownType : methodType.getThrownTypes()) {
    thrownTypes.add(MoreTypes.equivalence().wrap(thrownType));
  }
  return new AutoValue_MethodSignature(
      methodName,
      parameters.build(),
      thrownTypes.build());
}
 
Example 15
Source File: ControllerAnnotationValidator.java    From nalu with Apache License 2.0 4 votes vote down vote up
public void validate()
    throws ProcessorException {
  TypeElement typeElement = (TypeElement) this.controllerElement;
  // @Controller can only be used on a class
  if (!typeElement.getKind()
                  .isClass()) {
    throw new ProcessorException("Nalu-Processor: @Controller can only be used with an class");
  }
  // @Controller can only be used on a interface that extends IsController
  if (!this.processorUtils.extendsClassOrInterface(this.processingEnvironment.getTypeUtils(),
                                                   typeElement.asType(),
                                                   this.processingEnvironment.getElementUtils()
                                                                             .getTypeElement(IsController.class.getCanonicalName())
                                                                             .asType())) {
    throw new ProcessorException("Nalu-Processor: @Controller can only be used on a class that extends IsController or IsShell");
  }
  // check if route start with "/"
  Controller controllerAnnotation = controllerElement.getAnnotation(Controller.class);
  if (!controllerAnnotation.route()
                           .startsWith("/")) {
    throw new ProcessorException("Nalu-Processor: @Controller - route attribute muss begin with a '/'");
  }
  // validate route
  validateRoute();
  // AcceptParameter annotation
  List<String> parametersFromRoute = this.getParametersFromRoute(controllerAnnotation.route());
  for (Element element : this.processingEnvironment.getElementUtils()
                                                   .getAllMembers((TypeElement) this.controllerElement)) {
    if (ElementKind.METHOD.equals(element.getKind())) {
      if (!Objects.isNull(element.getAnnotation(AcceptParameter.class))) {
        AcceptParameter annotation = element.getAnnotation(AcceptParameter.class);
        if (!parametersFromRoute.contains(annotation.value())) {
          throw new ProcessorException("Nalu-Processor: controller >>" + controllerElement.toString() + "<< - @AcceptParameter with value >>" + annotation.value() + "<< is not represented in the route as parameter");
        }
        ExecutableType executableType = (ExecutableType) element.asType();
        List<? extends TypeMirror> parameters = executableType.getParameterTypes();
        if (parameters.size() != 1) {
          throw new ProcessorException("Nalu-Processor: controller >>" + controllerElement.toString() + "<< - @AcceptParameter annotated on >>" + executableType.toString() + "<< need one parameter of type String");
        }
        if (!String.class.getCanonicalName()
                         .equals(parameters.get(0)
                                           .toString())) {
          throw new ProcessorException("Nalu-Processor: controller >>" + controllerElement.toString() + "<< - @AcceptParameter on >>" + element.toString() + "<< parameter has the wrong type -> must be a String");
        }
      }
    }
  }
}
 
Example 16
Source File: ComponentDescriptor.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
private ComponentMethodDescriptor getDescriptorForComponentMethod(TypeElement componentElement,
    Kind componentKind,
    ExecutableElement componentMethod) {
  ExecutableType resolvedComponentMethod = MoreTypes.asExecutable(types.asMemberOf(
      MoreTypes.asDeclared(componentElement.asType()), componentMethod));
  TypeMirror returnType = resolvedComponentMethod.getReturnType();
  if (returnType.getKind().equals(DECLARED)) {
    if (MoreTypes.isTypeOf(Provider.class, returnType)
        || MoreTypes.isTypeOf(Lazy.class, returnType)) {
      return new AutoValue_ComponentDescriptor_ComponentMethodDescriptor(
          ComponentMethodKind.PROVISON,
          Optional.of(dependencyRequestFactory.forComponentProvisionMethod(componentMethod,
              resolvedComponentMethod)),
          componentMethod);
    } else if (MoreTypes.isTypeOf(MembersInjector.class, returnType)) {
      return new AutoValue_ComponentDescriptor_ComponentMethodDescriptor(
          ComponentMethodKind.MEMBERS_INJECTION,
          Optional.of(dependencyRequestFactory.forComponentMembersInjectionMethod(
              componentMethod,
              resolvedComponentMethod)),
          componentMethod);
    } else if (getAnnotationMirror(MoreTypes.asElement(returnType), Subcomponent.class)
        .isPresent()) {
      return new AutoValue_ComponentDescriptor_ComponentMethodDescriptor(
          ComponentMethodKind.SUBCOMPONENT,
          Optional.<DependencyRequest>absent(),
          componentMethod);
    }
  }

  // a typical provision method
  if (componentMethod.getParameters().isEmpty()
      && !componentMethod.getReturnType().getKind().equals(VOID)) {
    switch (componentKind) {
      case COMPONENT:
        return new AutoValue_ComponentDescriptor_ComponentMethodDescriptor(
            ComponentMethodKind.PROVISON,
            Optional.of(dependencyRequestFactory.forComponentProvisionMethod(componentMethod,
                resolvedComponentMethod)),
            componentMethod);
      case PRODUCTION_COMPONENT:
        return new AutoValue_ComponentDescriptor_ComponentMethodDescriptor(
            ComponentMethodKind.PRODUCTION,
            Optional.of(dependencyRequestFactory.forComponentProductionMethod(componentMethod,
                resolvedComponentMethod)),
            componentMethod);
      default:
        throw new AssertionError();
    }
  }

  List<? extends TypeMirror> parameterTypes = resolvedComponentMethod.getParameterTypes();
  if (parameterTypes.size() == 1
      && (returnType.getKind().equals(VOID)
          || MoreTypes.equivalence().equivalent(returnType, parameterTypes.get(0)))) {
    return new AutoValue_ComponentDescriptor_ComponentMethodDescriptor(
        ComponentMethodKind.MEMBERS_INJECTION,
        Optional.of(dependencyRequestFactory.forComponentMembersInjectionMethod(
            componentMethod,
            resolvedComponentMethod)),
        componentMethod);
  }

  throw new IllegalArgumentException("not a valid component method: " + componentMethod);
}
 
Example 17
Source File: ComponentMethodDescriptor.java    From bullet with Apache License 2.0 4 votes vote down vote up
static Optional<ComponentMethodDescriptor> forComponentMethod(Types types, DeclaredType componentElement, ExecutableElement componentMethod) {
  // Using same algorithm as Dagger's ComponentDescriptor#getDescriptorForComponentMethod
  ExecutableType resolvedComponentMethod = MoreTypes.asExecutable(types.asMemberOf(componentElement, componentMethod));
  TypeMirror returnType = resolvedComponentMethod.getReturnType();
  if (returnType.getKind() == TypeKind.DECLARED) {
    if (MoreTypes.isTypeOf(Provider.class, returnType)
        || MoreTypes.isTypeOf(Lazy.class, returnType)) {
      return methodDescriptor(
          ComponentMethodKind.PROVIDER_OR_LAZY,
          MoreTypes.asDeclared(MoreTypes.asDeclared(returnType).getTypeArguments().get(0)),
          componentMethod);
    } else if (MoreTypes.isTypeOf(MembersInjector.class, returnType)) {
      return methodDescriptor(
          ComponentMethodKind.MEMBERS_INJECTOR,
          MoreTypes.asDeclared(MoreTypes.asDeclared(returnType).getTypeArguments().get(0)),
          componentMethod);
    } else if (MoreElements.getAnnotationMirror(types.asElement(returnType), Subcomponent.class).isPresent()) {
      // Ignore subcomponent methods
      return Optional.absent();
    }
  }

  if (resolvedComponentMethod.getParameterTypes().isEmpty()
      && resolvedComponentMethod.getReturnType().getKind() == TypeKind.DECLARED) {
    return methodDescriptor(
        ComponentMethodKind.SIMPLE_PROVISION,
        MoreTypes.asDeclared(returnType),
        componentMethod);
  }

  List<? extends TypeMirror> parameterTypes = resolvedComponentMethod.getParameterTypes();
  if (parameterTypes.size() == 1
      && parameterTypes.get(0).getKind() == TypeKind.DECLARED
      && (returnType.getKind().equals(TypeKind.VOID)
          || types.isSameType(returnType, parameterTypes.get(0)))) {
    return methodDescriptor(
        ComponentMethodKind.SIMPLE_MEMBERS_INJECTION,
        MoreTypes.asDeclared(parameterTypes.get(0)),
        componentMethod);
  }

  // Let Dagger do the validation
  return Optional.absent();
}
 
Example 18
Source File: AdapterDescriptor.java    From paperparcel with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("ConstantConditions") // Already validated
private Optional<ConstructorInfo> getConstructorInfo(
    TypeElement adapterElement, DeclaredType resolvedAdapterType, boolean allowSerializable) {

  ExecutableElement mainConstructor = Utils.findLargestPublicConstructor(adapterElement);
  if (mainConstructor == null) return Optional.absent();

  ImmutableList.Builder<ConstructorInfo.Param> parameterBuilder = ImmutableList.builder();

  ExecutableType resolvedConstructorType =
      MoreTypes.asExecutable(types.asMemberOf(resolvedAdapterType, mainConstructor));
  List<? extends TypeMirror> resolveParameterList = resolvedConstructorType.getParameterTypes();
  List<? extends VariableElement> parameters = mainConstructor.getParameters();

  for (int i = 0; i < parameters.size(); i++) {
    VariableElement dependencyElement = parameters.get(i);
    TypeMirror resolvedDependencyType = resolveParameterList.get(i);

    if (Utils.isAdapterType(dependencyElement, elements, types)) {
      TypeMirror dependencyAdaptedType =
          Utils.getAdaptedType(elements, types, MoreTypes.asDeclared(resolvedDependencyType));
      AdapterDescriptor adapterDependency = create(dependencyAdaptedType, allowSerializable);
      if (adapterDependency == null) {
        return Optional.absent();
      }
      parameterBuilder.add(new ConstructorInfo.AdapterParam(adapterDependency));

    } else if (Utils.isCreatorType(dependencyElement, elements, types)) {
      TypeMirror creatorArg =
          Utils.getCreatorArg(elements, types, MoreTypes.asDeclared(resolvedDependencyType));
      VariableElement creator = Utils.findCreator(elements, types, creatorArg);
      ClassName creatorOwner = null;
      boolean requiresCast = false;
      if (creator != null) {
        TypeElement creatorOwnerElement = (TypeElement) creator.getEnclosingElement();
        // Must only pass the CREATOR directly if the Parcelable element is final. Otherwise
        // we need to use Parcel.readParcelable to read Parcelables because it supports
        // polymorphic types. The reason why we pass the CREATOR at all is because it is a
        // lot faster (no runtime reflection involved). This optimisation will occur in most
        // cases in kotlin (as classes are final by default, and will always occur when using
        // the AutoValueExtension).
        if (creatorOwnerElement.getModifiers().contains(Modifier.FINAL)) {
          creatorOwner = ClassName.get(creatorOwnerElement);
        }
        // Require a cast if the creator owner is generic.
        // See https://github.com/grandstaish/paperparcel/issues/193
        if (creatorOwnerElement.getTypeParameters().size() > 0) {
          requiresCast = true;
        }
      }
      parameterBuilder.add(new ConstructorInfo.CreatorParam(creatorOwner, requiresCast));

    } else {
      TypeMirror classArg =
          Utils.getClassArg(elements, types, MoreTypes.asDeclared(resolvedDependencyType));
      TypeName classTypeName = TypeName.get(classArg);
      parameterBuilder.add(new ConstructorInfo.ClassParam(classTypeName));
    }
  }

  return Optional.of(ConstructorInfo.create(parameterBuilder.build()));
}
 
Example 19
Source File: ComponentProcessor.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
private Property executableElementToProperty(Element element, String componentInfoName) {
  String propertyName = element.getSimpleName().toString();
  SimpleProperty simpleProperty = element.getAnnotation(SimpleProperty.class);

  if (!(element.asType() instanceof ExecutableType)) {
    throw new RuntimeException("element.asType() is not an ExecutableType for " +
                               propertyName);
  }

  // Use Javadoc for property unless description is set to a non-empty string.
  String description = elementUtils.getDocComment(element);
  String longDescription = description;
  if (!simpleProperty.description().isEmpty()) {
    description = simpleProperty.description();
  }
  if (description == null) {
    description = "";
  }
  // Read only until the first javadoc parameter
  description = description.split("[^\\\\][@{]")[0].trim();

  Property property = new Property(propertyName,
                                   description,
                                   longDescription,
                                   simpleProperty.category(),
                                   simpleProperty.userVisible(),
                                   elementUtils.isDeprecated(element));

  // Get parameters to tell if this is a getter or setter.
  ExecutableType executableType = (ExecutableType) element.asType();
  List<? extends TypeMirror> parameters = executableType.getParameterTypes();

  // Check if it is a setter or getter, and set the property's readable, writable,
  // and type fields appropriately.
  TypeMirror typeMirror;
  if (parameters.size() == 0) {
    // It is a getter.
    property.readable = true;
    typeMirror = executableType.getReturnType();
    if (typeMirror.getKind().equals(TypeKind.VOID)) {
      throw new RuntimeException("Property method is void and has no parameters: "
                                 + propertyName);
    }
    if (element.getAnnotation(IsColor.class) != null) {
      property.color = true;
    }
  } else {
    // It is a setter.
    property.writable = true;
    if (parameters.size() != 1) {
      throw new RuntimeException("Too many parameters for setter for " +
                                 propertyName);
    }
    typeMirror = parameters.get(0);
    for (VariableElement ve : ((ExecutableElement) element).getParameters()) {
      if (ve.getAnnotation(IsColor.class) != null) {
        property.color = true;
      }
    }
  }

  // Use typeMirror to set the property's type.
  if (!typeMirror.getKind().equals(TypeKind.VOID)) {
    property.type = typeMirror.toString();
    updateComponentTypes(typeMirror);
  }

  property.componentInfoName = componentInfoName;

  return property;
}
 
Example 20
Source File: SourceModeler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private RestEntity getParamEntity( CompilationController controller,
        Collection<TypeMirror> boxedPrimitives, 
        ExecutableElement methodElement, ExecutableType method )

{
    List<? extends VariableElement> parameters = methodElement.getParameters();
    int index=-1;
    int i=0;
    for (VariableElement variableElement : parameters) {
        List<? extends AnnotationMirror> annotationMirrors = 
            variableElement.getAnnotationMirrors();
        boolean isUriParam = false;
        for (AnnotationMirror annotationMirror : annotationMirrors) {
            DeclaredType annotationType = annotationMirror.getAnnotationType();
            Element annotationElement = annotationType.asElement();
            if ( annotationElement instanceof TypeElement ){
                String fqn = ((TypeElement)annotationElement).
                    getQualifiedName().toString();
                // skip arguments which are URI parameters ( query param or path param )
                if ( fqn.equals(RestConstants.QUERY_PARAM) || 
                        fqn.equals(RestConstants.PATH_PARAM))
                {
                    isUriParam = true;
                    break;
                }
            }
        }
        if ( !isUriParam ){
            index = i;
            break;
        }
        i++;
    }
    
    if ( index==-1 ){
        return new RestEntity(true);
    }
    List<? extends TypeMirror> parameterTypes = method.getParameterTypes();
    TypeMirror typeMirror = parameterTypes.get( index );
    return getRestEntity(controller, boxedPrimitives, typeMirror);
}