Java Code Examples for javax.lang.model.element.ExecutableElement#getKind()

The following examples show how to use javax.lang.model.element.ExecutableElement#getKind() . These examples are extracted from open source projects. 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
public static GeneratedExecutableElement mutableCopy(String selector, ExecutableElement method) {
  GeneratedExecutableElement generatedMethod =
      new GeneratedExecutableElement(
          method.getSimpleName().toString(),
          selector,
          method.getKind(),
          method.getReturnType(),
          method.getEnclosingElement(),
          method.isVarArgs(),
          ElementUtil.isSynthetic(method));
  generatedMethod.addAnnotationMirrors(method.getAnnotationMirrors());
  generatedMethod.addModifiers(method.getModifiers());
  generatedMethod.parameters.addAll(method.getParameters());
  generatedMethod.thrownTypes.addAll(method.getThrownTypes());
  generatedMethod.typeParameters.addAll(method.getTypeParameters());
  return generatedMethod;
}
 
Example 2
/**
 * Visits an executable element, dispatching to the visit method
 * for the specific {@linkplain ElementKind kind} of executable,
 * {@code CONSTRUCTOR}, {@code INSTANCE_INIT}, {@code METHOD}, or
 * {@code STATIC_INIT}.
 *
 * @param e {@inheritDoc}
 * @param p {@inheritDoc}
 * @return  the result of the kind-specific visit method
 */
@Override
public R visitExecutable(ExecutableElement e, P p) {
    ElementKind k = e.getKind();
    switch(k) {
    case CONSTRUCTOR:
        return visitExecutableAsConstructor(e, p);

    case INSTANCE_INIT:
        return visitExecutableAsInstanceInit(e, p);

    case METHOD:
        return visitExecutableAsMethod(e, p);

    case STATIC_INIT:
        return visitExecutableAsStaticInit(e, p);

    default:
        throw new AssertionError("Bad kind " + k + " for ExecutableElement" + e);
    }
}
 
Example 3
private boolean isLambdaAnAmbiguousArgument(ExecutableElement invokingElement, int indexOfLambdaInArgs) {
    
    Element classOfInvokingElement = invokingElement.getEnclosingElement();
    for (Element possibleMatchingElement : info.getElementUtilities().getMembers(classOfInvokingElement.asType(), null)) {

        //ignore invoking element
        if (possibleMatchingElement == invokingElement) {
            continue;
        }

        if (possibleMatchingElement.getKind() != invokingElement.getKind()) {
            continue;
        }

        if (doesInvokingElementMatchFound(invokingElement,
                (ExecutableElement) possibleMatchingElement, indexOfLambdaInArgs)) {
            return true;
        }
    }

    return false;
}
 
Example 4
Source Project: netbeans   File: JavadocCompletionItem.java    License: Apache License 2.0 6 votes vote down vote up
public JavadocExecutableItem(CompletionItem jmethod,
        ExecutableElement ee, int substitutionOffset) {
    
    this.delegate = jmethod;
    this.substitutionOffset = substitutionOffset;
    
    this.name = ee.getKind() == ElementKind.METHOD
            ? ee.getSimpleName()
            : ee.getEnclosingElement().getSimpleName();
    
    List<? extends VariableElement> params = ee.getParameters();
    this.paramTypes = new String[params.size()];
    int i = 0;
    for (VariableElement p : params) {
        TypeMirror asType = p.asType();
        this.paramTypes[i++] = resolveTypeName(asType, ee.isVarArgs()).toString();
    }
}
 
Example 5
Source Project: netbeans   File: ElementUtilitiesEx.java    License: Apache License 2.0 6 votes vote down vote up
public static String getBinaryName(ExecutableElement method, CompilationInfo ci) {
    try {
        switch (method.getKind()) {
            case METHOD:
            case CONSTRUCTOR:
            case STATIC_INIT:

                //case INSTANCE_INIT: // not supported
                String paramsVMSignature = getParamsSignature(method.getParameters(), ci);
                String retTypeVMSignature = VMUtils.typeToVMSignature(getRealTypeName(method.getReturnType(), ci));

                return "(" + paramsVMSignature + ")" + retTypeVMSignature; //NOI18N
            default:
                return null;
        }

    } catch (IllegalArgumentException e) {
        ProfilerLogger.warning(e.getMessage());
    }

    return null;
}
 
Example 6
Source Project: netbeans   File: ElementUtilitiesEx.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Compares the desired textual method name with a name of particualt executable element (method, constructor ...)
     * @param vmName The name to match against. Can be a real method name, "<init>" or "<cinit>"
     * @param ee The executable element to use in matching
     * @return Returns true if the given textual name matches the name of the executable element
     */
    private static boolean methodNameMatch(final String vmName,
            final ExecutableElement ee) {
        switch (ee.getKind()) {
            // for method use textual name matching
            case METHOD:
                return ee.getSimpleName().contentEquals(vmName);

            // for constructor use the special <init> name
            case CONSTRUCTOR:
                return vmName.equals(VM_CONSTRUCTUR_SIG);

            // for initializer use the special <cinit> name
            case STATIC_INIT:
            case INSTANCE_INIT:
                return vmName.equals(VM_INITIALIZER_SIG);
        }

// default fail-over
        return false;
    }
 
Example 7
Source Project: netbeans   File: AbstractTestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 */
private boolean isTestableMethod(ExecutableElement method) {
    if (method.getKind() != ElementKind.METHOD) {
        throw new IllegalArgumentException();
    }

    return setup.isMethodTestable(method);
}
 
Example 8
Source Project: netbeans   File: AbstractTestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 */
private boolean isTestableMethod(ExecutableElement method) {
    if (method.getKind() != ElementKind.METHOD) {
        throw new IllegalArgumentException();
    }

    return setup.isMethodTestable(method);
}
 
Example 9
private Collection<ColoringAttributes> getMethodColoring(ExecutableElement mdecl) {
    Collection<ColoringAttributes> c = new ArrayList<ColoringAttributes>();
    
    addModifiers(mdecl, c);
    
    if (mdecl.getKind() == ElementKind.CONSTRUCTOR) {
        c.add(ColoringAttributes.CONSTRUCTOR);
    } else
        c.add(ColoringAttributes.METHOD);
    
    return c;
}
 
Example 10
Source Project: FreeBuilder   File: BuildableType.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isCallableMethod(ExecutableElement element) {
  boolean isMethod = (element.getKind() == ElementKind.METHOD);
  boolean isPublic = element.getModifiers().contains(Modifier.PUBLIC);
  boolean isNotStatic = !element.getModifiers().contains(Modifier.STATIC);
  boolean declaresNoExceptions = element.getThrownTypes().isEmpty();
  return isMethod && isPublic && isNotStatic && declaresNoExceptions;
}
 
Example 11
Source Project: soabase-halva   File: PassCreate.java    License: Apache License 2.0 5 votes vote down vote up
private void addItem(TypeSpec.Builder builder, ImplicitSpec spec, ImplicitItem item)
{
    ExecutableElement method = item.getExecutableElement();
    MethodSpec.Builder methodSpecBuilder = (method.getKind() == ElementKind.CONSTRUCTOR) ? MethodSpec.constructorBuilder() : MethodSpec.methodBuilder(method.getSimpleName().toString());
    methodSpecBuilder.addModifiers(method.getModifiers().stream().filter(m -> m != Modifier.ABSTRACT).collect(Collectors.toList()));
    if ( method.getReturnType().getKind() != TypeKind.VOID )
    {
        methodSpecBuilder.returns(ClassName.get(method.getReturnType()));
    }
    method.getTypeParameters().forEach(typeParameter -> methodSpecBuilder.addTypeVariable(TypeVariableName.get(typeParameter)));

    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
    if ( method.getKind() == ElementKind.CONSTRUCTOR )
    {
        codeBlockBuilder.add("super(");
    }
    else if ( method.getReturnType().getKind() == TypeKind.VOID )
    {
        codeBlockBuilder.add("super.$L(", method.getSimpleName());
    }
    else
    {
        codeBlockBuilder.add("return super.$L(", method.getSimpleName());
    }

    CodeBlock methodCode = new ImplicitMethod(environment, method, spec, contextItems).build(parameter -> {
        ParameterSpec.Builder parameterSpec = ParameterSpec.builder(ClassName.get(parameter.asType()), parameter.getSimpleName().toString(), parameter.getModifiers().toArray(new javax.lang.model.element.Modifier[parameter.getModifiers().size()]));
        methodSpecBuilder.addParameter(parameterSpec.build());
    });
    codeBlockBuilder.add(methodCode);
    methodSpecBuilder.addCode(codeBlockBuilder.addStatement(")").build());
    builder.addMethod(methodSpecBuilder.build());
}
 
Example 12
Source Project: netbeans   File: ElementNode.java    License: Apache License 2.0 5 votes vote down vote up
private static String createHtmlHeader(boolean deprecated, ExecutableElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        sb.append(e.getEnclosingElement().getSimpleName());
    } else {
        sb.append(e.getSimpleName());
    }
    if (deprecated) sb.append("</s>");
    sb.append("("); // NOI18N
    for(Iterator<? extends VariableElement> it = e.getParameters().iterator(); it.hasNext(); ) {
        VariableElement param = it.next();
        if (!it.hasNext() && e.isVarArgs() && param.asType().getKind() == TypeKind.ARRAY) {
            sb.append(translateToHTML(print(((ArrayType) param.asType()).getComponentType())));
            sb.append("...");
        } else {
            sb.append(translateToHTML(print(param.asType())));
        }
        sb.append(" "); // NOI18N
        sb.append(param.getSimpleName());
        if (it.hasNext()) {
            sb.append(", "); // NOI18N
        }
    }
    sb.append(")"); // NOI18N
    if ( e.getKind() != ElementKind.CONSTRUCTOR ) {
        TypeMirror rt = e.getReturnType();
        if ( rt.getKind() != TypeKind.VOID ) {
            sb.append(" : "); // NOI18N
            sb.append(translateToHTML(print(e.getReturnType())));
        }
    }
    return sb.toString();
}
 
Example 13
Source Project: netbeans   File: GoToSupport.java    License: Apache License 2.0 5 votes vote down vote up
Void printExecutable(ExecutableElement e, DeclaredType dt, Boolean highlightName) {
    switch (e.getKind()) {
        case CONSTRUCTOR:
            modifier(e.getModifiers());
            dumpTypeArguments(e.getTypeParameters());
            result.append(' ');
            boldStartCheck(highlightName);
            result.append(e.getEnclosingElement().getSimpleName());
            boldStopCheck(highlightName);
            TypeMirror memberType = null;
            if (dt != null) {
                dumpRealTypeArguments(dt.getTypeArguments());
                try {
                    memberType = info.getTypes().asMemberOf(dt, e);
                } catch (IllegalStateException ise) {}
            }
            if (memberType instanceof ExecutableType) {
                dumpArguments(e.getParameters(), ((ExecutableType) memberType).getParameterTypes());
            } else {
                dumpArguments(e.getParameters(), null);
            }
            dumpThrows(e.getThrownTypes());
            break;
        case METHOD:
            modifier(e.getModifiers());
            dumpTypeArguments(e.getTypeParameters());
            result.append(getTypeName(info, e.getReturnType(), true));
            result.append(' ');
            boldStartCheck(highlightName);
            result.append(e.getSimpleName());
            boldStopCheck(highlightName);
            dumpArguments(e.getParameters(), null);
            dumpThrows(e.getThrownTypes());
            break;
        case INSTANCE_INIT:
        case STATIC_INIT:
            //these two cannot be referenced anyway...
    }
    return null;
}
 
Example 14
Source Project: squidb   File: ModelMethodPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private void checkExecutableElement(ExecutableElement e, List<ExecutableElement> modelMethods,
        List<ExecutableElement> staticModelMethods, DeclaredTypeName modelClass) {
    Set<Modifier> modifiers = e.getModifiers();
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        // Don't copy constructors
        return;
    }
    if (!modifiers.contains(Modifier.STATIC)) {
        utils.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "Model spec objects should never be instantiated, so non-static methods are meaningless. " +
                        "Did you mean to make this a static method?", e);
        return;
    }
    ModelMethod methodAnnotation = e.getAnnotation(ModelMethod.class);
    // Private static methods may be unannotated if they are called by a public annotated method.
    // Don't assume error if method is private
    if (methodAnnotation == null) {
        if (modifiers.contains(Modifier.PUBLIC)) {
            staticModelMethods.add(e);
        } else if (!modifiers.contains(Modifier.PRIVATE)) {
            utils.getMessager().printMessage(Diagnostic.Kind.WARNING,
                    "This method will not be added to the model definition. " +
                            "Did you mean to annotate this method with @ModelMethod?", e);
        }
    } else {
        List<? extends VariableElement> params = e.getParameters();
        if (params.size() == 0) {
            modelSpec.logError("@ModelMethod methods must have an abstract model as their first argument", e);
        } else {
            VariableElement firstParam = params.get(0);
            TypeMirror paramType = firstParam.asType();
            if (!checkFirstArgType(paramType, modelClass)) {
                modelSpec.logError("@ModelMethod methods must have an abstract model as their first argument", e);
            } else {
                modelMethods.add(e);
            }
        }
    }
}
 
Example 15
Source Project: netbeans   File: ELHyperlinkProvider.java    License: Apache License 2.0 5 votes vote down vote up
Void printExecutable(ExecutableElement e, DeclaredType dt, Boolean highlightName) {
    switch (e.getKind()) {
        case CONSTRUCTOR:
            modifier(e.getModifiers());
            dumpTypeArguments(e.getTypeParameters());
            result.append(' ');
            boldStartCheck(highlightName);
            result.append(e.getEnclosingElement().getSimpleName());
            boldStopCheck(highlightName);
            if (dt != null) {
                dumpRealTypeArguments(dt.getTypeArguments());
                dumpArguments(e.getParameters(), ((ExecutableType) info.getTypes().asMemberOf(dt, e)).getParameterTypes());
            } else {
                dumpArguments(e.getParameters(), null);
            }
            dumpThrows(e.getThrownTypes());
            break;
        case METHOD:
            modifier(e.getModifiers());
            dumpTypeArguments(e.getTypeParameters());
            result.append(getTypeName(info, e.getReturnType(), true));
            result.append(' ');
            boldStartCheck(highlightName);
            result.append(e.getSimpleName());
            boldStopCheck(highlightName);
            dumpArguments(e.getParameters(), null);
            dumpThrows(e.getThrownTypes());
            break;
        case INSTANCE_INIT:
        case STATIC_INIT:
            //these two cannot be referenced anyway...
    }
    return null;
}
 
Example 16
Source Project: netbeans   File: ActionProcessor.java    License: Apache License 2.0 4 votes vote down vote up
private TypeMirror generateContext(Element e, File f, ActionRegistration ar) throws LayerGenerationException {
    ExecutableElement ee = null;
    ExecutableElement candidate = null;
    for (ExecutableElement element : ElementFilter.constructorsIn(e.getEnclosedElements())) {
        if (element.getKind() == ElementKind.CONSTRUCTOR) {
            candidate = element;
            if (!element.getModifiers().contains(Modifier.PUBLIC)) {
                continue;
            }
            if (ee != null) {
                throw new LayerGenerationException("Only one public constructor allowed", e, processingEnv, ar); // NOI18N
            }
            ee = element;
        }

    }
    
    if (ee == null || ee.getParameters().size() != 1) {
        if (candidate != null) {
            throw new LayerGenerationException("Constructor has to be public with one argument", candidate);
        }
        throw new LayerGenerationException("Constructor must have one argument", ee);
    }

    VariableElement ve = (VariableElement)ee.getParameters().get(0);
    TypeMirror ctorType = ve.asType();
    switch (ctorType.getKind()) {
    case ARRAY:
        String elemType = ((ArrayType) ctorType).getComponentType().toString();
        throw new LayerGenerationException("Use List<" + elemType + "> rather than " + elemType + "[] in constructor", e, processingEnv, ar);
    case DECLARED:
        break; // good
    default:
        throw new LayerGenerationException("Must use SomeType (or List<SomeType>) in constructor, not " + ctorType.getKind());
    }
    DeclaredType dt = (DeclaredType) ctorType;
    String dtName = processingEnv.getElementUtils().getBinaryName((TypeElement)dt.asElement()).toString();
    if ("java.util.List".equals(dtName)) {
        if (dt.getTypeArguments().isEmpty()) {
            throw new LayerGenerationException("Use List<SomeType>", ee);
        }
        f.stringvalue("type", binaryName(dt.getTypeArguments().get(0)));
        f.methodvalue("delegate", "org.openide.awt.Actions", "inject");
        f.stringvalue("injectable", processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString());
        f.stringvalue("selectionType", "ANY");
        f.methodvalue("instanceCreate", "org.openide.awt.Actions", "context");
        return dt.getTypeArguments().get(0);
    }
    if (!dt.getTypeArguments().isEmpty()) {
        throw new LayerGenerationException("No type parameters allowed in ", ee);
    }

    f.stringvalue("type", binaryName(ctorType));
    f.methodvalue("delegate", "org.openide.awt.Actions", "inject");
    f.stringvalue("injectable", processingEnv.getElementUtils().getBinaryName((TypeElement)e).toString());
    f.stringvalue("selectionType", "EXACTLY_ONE");
    f.methodvalue("instanceCreate", "org.openide.awt.Actions", "context");
    return ctorType;
}
 
Example 17
Source Project: immutables   File: Proto.java    License: Apache License 2.0 4 votes vote down vote up
static boolean suitableForBuilderConstructor(ExecutableElement element) {
  return element.getKind() == ElementKind.CONSTRUCTOR
      && !element.getModifiers().contains(Modifier.PRIVATE);
}
 
Example 18
Source Project: j2cl   File: JavaEnvironment.java    License: Apache License 2.0 4 votes vote down vote up
private MethodDescriptor createDeclaredMethodDescriptor(
    DeclaredTypeDescriptor enclosingTypeDescriptor,
    ExecutableElement declarationMethodElement,
    MethodDescriptor declarationMethodDescriptor,
    List<TypeDescriptor> parameters,
    TypeDescriptor returnTypeDescriptor) {
  List<TypeVariable> typeParameterTypeDescriptors =
      declarationMethodElement.getTypeParameters().stream()
          .map(Element::asType)
          .map(this::createTypeDescriptor)
          .map(TypeVariable.class::cast)
          .collect(toImmutableList());

  boolean isStatic = isStatic(declarationMethodElement);
  Visibility visibility = getVisibility(declarationMethodElement);
  boolean isDefault = isDefaultMethod(declarationMethodElement);
  JsInfo jsInfo = computeJsInfo(declarationMethodElement);

  boolean isNative =
      isNative(declarationMethodElement)
          || (!jsInfo.isJsOverlay()
              && enclosingTypeDescriptor.isNative()
              && isAbstract(declarationMethodElement));

  boolean isConstructor = declarationMethodElement.getKind() == ElementKind.CONSTRUCTOR;
  String methodName = declarationMethodElement.getSimpleName().toString();

  ImmutableList.Builder<ParameterDescriptor> parameterDescriptorBuilder = ImmutableList.builder();
  for (int i = 0; i < parameters.size(); i++) {
    parameterDescriptorBuilder.add(
        ParameterDescriptor.newBuilder()
            .setTypeDescriptor(parameters.get(i))
            .setJsOptional(JsInteropUtils.isJsOptional(declarationMethodElement, i))
            .setVarargs(i == parameters.size() - 1 && declarationMethodElement.isVarArgs())
            .setDoNotAutobox(JsInteropUtils.isDoNotAutobox(declarationMethodElement, i))
            .build());
  }

  if (enclosingTypeDescriptor.getTypeDeclaration().isAnonymous()
      && isConstructor
      && enclosingTypeDescriptor.getSuperTypeDescriptor().hasJsConstructor()) {
    jsInfo = JsInfo.Builder.from(jsInfo).setJsMemberType(JsMemberType.CONSTRUCTOR).build();
  }
  return MethodDescriptor.newBuilder()
      .setEnclosingTypeDescriptor(enclosingTypeDescriptor)
      .setName(isConstructor ? null : methodName)
      .setParameterDescriptors(parameterDescriptorBuilder.build())
      .setDeclarationDescriptor(declarationMethodDescriptor)
      .setReturnTypeDescriptor(returnTypeDescriptor)
      .setTypeParameterTypeDescriptors(typeParameterTypeDescriptors)
      .setJsInfo(jsInfo)
      .setJsFunction(isOrOverridesJsFunctionMethod(declarationMethodElement))
      .setVisibility(visibility)
      .setStatic(isStatic)
      .setConstructor(isConstructor)
      .setNative(isNative)
      .setFinal(isFinal(declarationMethodElement))
      .setDefaultMethod(isDefault)
      .setAbstract(isAbstract(declarationMethodElement))
      .setSynthetic(isSynthetic(declarationMethodElement))
      .setEnumSyntheticMethod(isEnumSyntheticMethod(declarationMethodElement))
      .setUnusableByJsSuppressed(
          JsInteropAnnotationUtils.isUnusableByJsSuppressed(declarationMethodElement))
      .setDeprecated(isDeprecated(declarationMethodElement))
      .build();
}
 
Example 19
Source Project: XLog   File: XLogProcessor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    System.out.println("processing: " + env.toString());
    List<MethodToLog> methodToLogs = new ArrayList<>();
    List<String> classNames = new ArrayList<>();

    for (Element element : env.getElementsAnnotatedWith(XLog.class)) {
        if (element.getKind() != ElementKind.METHOD
                && element.getKind() != ElementKind.CONSTRUCTOR
                && element.getKind() != ElementKind.CLASS) {
            throw new IllegalStateException(
                    String.format("@%s annotation must be on as method, constructor or class.",
                            element.getSimpleName()));
        }
        if (element instanceof TypeElement) {
            // class
            String pkgName = ((TypeElement) element).getQualifiedName().toString();
            if (!classNames.contains(pkgName)) {
                classNames.add(pkgName);
            }
        } else if (element instanceof ExecutableElement) {
            // method or constructor
            ExecutableElement e = (ExecutableElement) element;

            int type = XLogUtils.TYPE_METHOD;
            if (e.getKind() == ElementKind.METHOD) {
                type = XLogUtils.TYPE_METHOD;
            } else if (e.getKind() == ElementKind.CONSTRUCTOR) {
                type = XLogUtils.TYPE_CONSTRUCTOR;
            }

            TypeElement te = findEnclosingTypeElement(e);
            System.out.println(te.getQualifiedName().toString() + "." + e.getSimpleName());
            System.out.println(e.getReturnType());
            List<String> parameters = new ArrayList<>();
            List<String> parameterNames = new ArrayList<>();
            for (VariableElement ve : e.getParameters()) {
                System.out.println(ve.asType());
                System.out.println(ve.getSimpleName());
                parameters.add(ve.asType().toString());
                parameterNames.add(ve.getSimpleName().toString());

            }
            MethodToLog methodToLog = new MethodToLog(type, te.getQualifiedName().toString(),
                    e.getSimpleName().toString(), parameters, parameterNames);
            methodToLogs.add(methodToLog);

            if (!classNames.contains(methodToLog.getClassName())) {
                classNames.add(methodToLog.getClassName());
            }
        }
    }

    if (methodToLogs.size() > 0) {
        generateXLogProcessor("_" + md5(env.toString()), methodToLogs, classNames);
    }

    return true;
}
 
Example 20
Source Project: openjdk-jdk9   File: Utils.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the TypeMirror of the ExecutableElement for all methods,
 * a null if constructor.
 * @param ee the ExecutableElement
 * @return
 */
public TypeMirror getReturnType(ExecutableElement ee) {
    return ee.getKind() == CONSTRUCTOR ? null : ee.getReturnType();
}