Java Code Examples for javax.lang.model.element.ExecutableElement

The following are top voted examples for showing how to use javax.lang.model.element.ExecutableElement. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: BiFeature.java   View source code 6 votes vote down vote up
Property( PropertyPattern pp, CompilationInfo javac, BiAnalyser bia ) throws GenerateBeanException {
    super( pp, bia );
    mode = pp.getMode();
    pattern = pp;

    TypeElement declaringClass = pattern.getDeclaringClass().resolve(javac);
    declaringClassName = declaringClass.getQualifiedName().toString();
    ElementHandle<ExecutableElement> getterHandle = pattern.getGetterMethod();
    getterName = getterHandle == null? null: getterHandle.resolve(javac).getSimpleName().toString();
    ElementHandle<ExecutableElement> setterHandle = pattern.getSetterMethod();
    setterName = setterHandle == null? null: setterHandle.resolve(javac).getSimpleName().toString();

    if (LOG.isLoggable(Level.FINE) && getClass() == Property.class) {
        debugTooltip = String.format("<html><body><b>Field:</b> %s<br><b>Getter:</b> %s<br><b>Setter:</b> %s</body></html>", // NOI18N
                pp.getEstimatedField() == null
                        ? null
                        : ElementHeaders.getHeader(pp.getEstimatedField().resolve(javac), javac, ElementHeaders.NAME +
                                " : " + ElementHeaders.TYPE) + " :: " + // NOI18N
                                ((TypeElement) pp.getEstimatedField().resolve(javac).getEnclosingElement()).getQualifiedName(),
                printMethodHandleTip(getterHandle, javac),
                printMethodHandleTip(setterHandle, javac)
                );
    }
}
 
Example 2
Project: RxPay   File: EntityHandler.java   View source code 6 votes vote down vote up
/**
 * handler method annotations
 *
 * @param element
 */
private void handlerMethod(ExecutableElement element) {
    if (onMethodRegulaListener != null) {
        String msg = onMethodRegulaListener.onRegula(element);
        if (!("".equals(msg) || msg == null)) {
            throwExceptionWithMsg(msg, element);
            return;
        }
    }
    MethodEntity methodEntity = new MethodEntity(element, typeUtils, elementUtils);

    printNormalMsg(methodEntity.toString());

    String className = methodEntity.getClassSimpleName();
    if (classEntityMap.get(className) == null){
        classEntityMap.put(className,
                new ClassEntity(elementUtils, typeUtils,
                        (TypeElement) element.getEnclosingElement()));
    }

    ClassEntity classEntity = classEntityMap.get(className);
    classEntity.addMethodEntity(methodEntity);
}
 
Example 3
Project: incubator-netbeans   File: ComputeImports.java   View source code 6 votes vote down vote up
public void addMethodFqn(Element el) {
    if (el.getKind() != ElementKind.METHOD) {
        return;
    }
    String fqn = info.getElementUtilities().getElementName(el, true).toString();
    List<Element> els = fqn2Methods.get(fqn);
    if (els == null) {
        els = new ArrayList<>(2);
        fqn2Methods.put(fqn, els);
    }
    els.add(el);
    String simpleName = ((ExecutableElement)el).getSimpleName().toString();
    Set<String> col = possibleMethodFQNs.get(simpleName);
    if (col == null) {
        col = new HashSet<>(3);
        possibleMethodFQNs.put(simpleName, col);
    }
    col.add(fqn);
}
 
Example 4
Project: vulture   File: VultureProcessor.java   View source code 6 votes vote down vote up
@TargetApi(24)
private Map<ExecutableElement, List<MethodParam>> getMethodToParams(List<ExecutableElement> methods) {
    return methods.stream()
            .collect(Collectors.toMap(
                    method -> method,
                    method -> {
                        AtomicInteger index = new AtomicInteger(0);
                        return method.getParameters()
                                .stream()
                                .map(varElm -> {
                                    String paramName = String.format(Locale.US, "arg%d", index.incrementAndGet());
                                    TypeName typeName = TypeName.get(varElm.asType());
                                    return MethodParam.of(paramName, typeName, varElm);
                                })
                                .collect(Collectors.toList());
                    }
            ));
}
 
Example 5
Project: incubator-netbeans   File: CompromiseSATest.java   View source code 6 votes vote down vote up
public void testConstructorSignatureFromElement () throws Exception {	
InputStream in = this.prepareData(TEST_CLASS);
try {
    JavacTask jt = prepareJavac ();
    Elements elements = jt.getElements();
    TypeElement be = elements.getTypeElement(TEST_CLASS);
    ClassFile cf = new ClassFile (in, true);
    String className = cf.getName().getInternalName().replace('/','.'); //NOI18N
    List<? extends Element> members = be.getEnclosedElements();
    for (Element e : members) {
	if (e.getKind() == ElementKind.CONSTRUCTOR) {
	    String[] msig = ClassFileUtil.createExecutableDescriptor((ExecutableElement) e);
	    assertEquals (className,msig[0]);
	    assertEquals (e.getSimpleName().toString(),msig[1]);
	    Method m = cf.getMethod (e.getSimpleName().toString(),msig[2]);
	    assertNotNull (m);
	}
    }
} finally {
    in.close ();
}
   }
 
Example 6
Project: GitHub   File: TypeStringProvider.java   View source code 6 votes vote down vote up
private boolean tryToUseSourceAsAWorkaround() {
  if (element.getKind() != ElementKind.METHOD) {
    // we don't bother with non-method attributes
    // (like factory builder, where attributes are parameters)
    return false;
  }

  CharSequence returnTypeString = SourceExtraction.getReturnTypeString((ExecutableElement) element);
  if (returnTypeString.length() == 0) {
    // no source could be extracted for some reason, workaround will not work
    return false;
  }

  Entry<String, List<String>> extractedTypes = SourceTypes.extract(returnTypeString);

  // forces source imports based resolution,
  // we should not rely that types would be fully qualified
  Entry<String, List<String>> resolvedTypes = resolveTypes(extractedTypes);

  this.rawTypeName = resolvedTypes.getKey();
  this.workaroundTypeParameters = resolvedTypes.getValue();
  this.workaroundTypeString = SourceTypes.stringify(resolvedTypes);

  // workaround may have successed, need to continue with whatever we have
  return true;
}
 
Example 7
Project: auto-value-variant   File: AutoValueVariantExtension.java   View source code 6 votes vote down vote up
@Override
public String generateClass(Context context, String className, String classToExtend, boolean isFinal) {
    String packageName = context.packageName();
    Name superName = context.autoValueClass().getSimpleName();
    Map<String, ExecutableElement> properties = context.properties();
    TypeName parametrizedType = getParametrizedType(context);

    TypeName variantName = parametrizedType == null ? TypeName.get(Object.class) : parametrizedType;
    TypeSpec subclass = TypeSpec.classBuilder(className)
            .addModifiers(isFinal ? Modifier.FINAL : Modifier.ABSTRACT)
            .superclass(ClassName.get(packageName, classToExtend))
            .addMethod(generateConstructor(properties))
            .addMethod(generateVariantOf(superName, variantName))
            .addMethod(generateVariantOfInGroup(superName, variantName))
            .addMethod(generateVariantOrEqual(superName, variantName))
            .addMethod(generateVariantOrEqualInGroup(superName, variantName))
            .addMethod(generateGroupFieldsEqual(TypeName.get(context.autoValueClass().asType()), properties))
            .build();

    JavaFile javaFile = JavaFile.builder(packageName, subclass).build();
    return javaFile.toString();
}
 
Example 8
Project: openjdk-jdk10   File: AbstractExecutableMemberWriter.java   View source code 6 votes vote down vote up
/**
 * Add exceptions for the executable member.
 *
 * @param member the member to write exceptions for.
 * @param htmltree the content tree to which the exceptions information will be added.
 */
protected void addExceptions(ExecutableElement member, Content htmltree, int indentSize) {
    List<? extends TypeMirror> exceptions = member.getThrownTypes();
    if (!exceptions.isEmpty()) {
        CharSequence indent = makeSpace(indentSize + 1 - 7);
        htmltree.addContent(DocletConstants.NL);
        htmltree.addContent(indent);
        htmltree.addContent("throws ");
        indent = makeSpace(indentSize + 1);
        Content link = writer.getLink(new LinkInfoImpl(configuration, MEMBER, exceptions.get(0)));
        htmltree.addContent(link);
        for(int i = 1; i < exceptions.size(); i++) {
            htmltree.addContent(",");
            htmltree.addContent(DocletConstants.NL);
            htmltree.addContent(indent);
            Content exceptionLink = writer.getLink(new LinkInfoImpl(configuration, MEMBER,
                    exceptions.get(i)));
            htmltree.addContent(exceptionLink);
        }
    }
}
 
Example 9
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 6 votes vote down vote up
private static List<? extends TypeMirror> computeReturn(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ReturnTree rt = (ReturnTree) parent.getLeaf();
    
    if (rt.getExpression() == error) {
        TreePath method = findMethod(parent);
        
        if (method == null) {
            return null;
        }
        
        Element el = info.getTrees().getElement(method);
        
        if (el == null || el.getKind() != ElementKind.METHOD) {
            return null;
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(((ExecutableElement) el).getReturnType());
    }
    
    return null;
}
 
Example 10
Project: incubator-netbeans   File: JavaUtils.java   View source code 6 votes vote down vote up
@NbBundle.Messages("JavaUtils.title.method.searching=Searching Method")
public static ElementHandle<ExecutableElement> findMethod(FileObject fileObject, final String classBinName,
        final String methodName, int argCount, Public publicFlag, Static staticFlag) {
    JavaSource js = JavaUtils.getJavaSource(fileObject);
    if (js != null) {
        MethodFinder methodFinder = new MethodFinder(js, classBinName, methodName, argCount, publicFlag, staticFlag);
        methodFinder.runAsUserTask();
        if (methodFinder.getMethodHandle() == null && SourceUtils.isScanInProgress()) {
            if (!ScanDialog.runWhenScanFinished(methodFinder, Bundle.JavaUtils_title_method_searching())) {
                return methodFinder.getMethodHandle();
            } else {
                return null;
            }
        } else {
            return methodFinder.getMethodHandle();
        }
    }

    return null;
}
 
Example 11
Project: incubator-netbeans   File: TooStrongCast.java   View source code 6 votes vote down vote up
private static boolean isPolymorphicSignature(CompilationInfo info, TreePath path) {
    TypeElement polymorphicEl=  info.getElements().getTypeElement("java.lang.invoke.MethodHandle.PolymorphicSignature"); // NOI18N
    if (polymorphicEl == null) {
        // unsuitable platform
        return false;
    }
    TypeMirror polyType = polymorphicEl.asType();
    Element target = info.getTrees().getElement(path);
    if (target == null || target.getKind() != ElementKind.METHOD) {
        return false;
    }
    if (target.getEnclosingElement() == null || !target.getEnclosingElement().getKind().isClass()) {
        return false;
    }
    ExecutableElement ee = (ExecutableElement)target;
    TypeElement parent = (TypeElement)target.getEnclosingElement();
    if (!parent.getQualifiedName().toString().startsWith("java.lang.invoke.")) { // NOI18N
        return false;
    }
    for (AnnotationMirror am : ee.getAnnotationMirrors()) {
        if (info.getTypes().isSameType(polyType, am.getAnnotationType())) {
            return true;
        }
    }
    return false;
}
 
Example 12
Project: android-auto-mapper   File: MoreElements.java   View source code 6 votes vote down vote up
private static void getLocalAndInheritedMethods(
        PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) {

    for (TypeMirror superInterface : type.getInterfaces()) {
        getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods);
    }
    if (type.getSuperclass().getKind() != TypeKind.NONE) {
        // Visit the superclass after superinterfaces so we will always see the implementation of a
        // method after any interfaces that declared it.
        getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods);
    }
    for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) {
        if (!method.getModifiers().contains(Modifier.STATIC)
                && methodVisibleFromPackage(method, pkg)) {
            methods.put(method.getSimpleName().toString(), method);
        }
    }
}
 
Example 13
Project: easybundler   File: BundlerClassInfo.java   View source code 6 votes vote down vote up
public BundlerClassInfo(TypeElement te) {
    typeElement = te;
    className = ClassName.get(typeElement);

    for (Element e : te.getEnclosedElements()) {
        if (e.getKind() == ElementKind.FIELD) {
            VariableElement ve = (VariableElement) e;
            fields.add(ve);
        }

        if (e.getKind() == ElementKind.METHOD) {
            ExecutableElement ee = (ExecutableElement) e;
            methods.add(ee);
        }
    }
}
 
Example 14
Project: openjdk-jdk10   File: LLNI.java   View source code 6 votes vote down vote up
protected final String jniMethodName(ExecutableElement method, String cname,
                                     boolean longName)
            throws TypeSignature.SignatureException {
    String res = "Java_" + cname + "_" + method.getSimpleName();

    if (longName) {
        TypeMirror mType =  types.erasure(method.getReturnType());
        List<? extends VariableElement> params = method.getParameters();
        List<TypeMirror> argTypes = new ArrayList<>();
        for (VariableElement param: params) {
            argTypes.add(types.erasure(param.asType()));
        }

        res = res + "__";
        for (TypeMirror t: argTypes) {
            String tname = t.toString();
            TypeSignature newTypeSig = new TypeSignature(elems);
            String sig = newTypeSig.getTypeSignature(tname);
            res = res + nameToIdentifier(sig);
        }
    }
    return res;
}
 
Example 15
Project: GitHub   File: RequestManagerGenerator.java   View source code 6 votes vote down vote up
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerRequestBuilderMethodOverride(
    ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  MethodSpec.Builder builder = ProcessorUtil.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(
          ProcessorUtil.generateCastingSuperCall(
              generatedRequestBuilderOfType, methodToOverride));

  for (AnnotationMirror mirror : methodToOverride.getAnnotationMirrors()) {
    builder.addAnnotation(AnnotationSpec.get(mirror));
  }
  return builder.build();
}
 
Example 16
Project: openjdk-jdk10   File: ConstructorBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the constructor documentation.
 *
 * @param memberDetailsTree the content tree to which the documentation will be added
 * @throws DocletException is there is a problem while building the documentation
 */
protected void buildConstructorDoc(Content memberDetailsTree) throws DocletException {
    if (writer == null) {
        return;
    }
    if (hasMembersToDocument()) {
        Content constructorDetailsTree = writer.getConstructorDetailsTreeHeader(typeElement,
                memberDetailsTree);

        Element lastElement = constructors.get(constructors.size() - 1);
        for (Element contructor : constructors) {
            currentConstructor = (ExecutableElement)contructor;
            Content constructorDocTree = writer.getConstructorDocTreeHeader(currentConstructor, constructorDetailsTree);

            buildSignature(constructorDocTree);
            buildDeprecationInfo(constructorDocTree);
            buildConstructorComments(constructorDocTree);
            buildTagInfo(constructorDocTree);

            constructorDetailsTree.addContent(writer.getConstructorDoc(constructorDocTree,
                    currentConstructor == lastElement));
        }
        memberDetailsTree.addContent(
                writer.getConstructorDetails(constructorDetailsTree));
    }
}
 
Example 17
Project: openjdk-jdk10   File: VisibleMemberMap.java   View source code 6 votes vote down vote up
/**
 * Return the key to the member map for the given member.
 */
private Object getMemberKey(Element element) {
    if (utils.isConstructor(element)) {
        return utils.getSimpleName(element) + utils.flatSignature((ExecutableElement)element);
    } else if (utils.isMethod(element)) {
        return getClassMember((ExecutableElement) element);
    } else if (utils.isField(element) || utils.isEnumConstant(element) || utils.isAnnotationType(element)) {
        return utils.getSimpleName(element);
    } else { // it's a class or interface
        String classOrIntName = utils.getSimpleName(element);
        //Strip off the containing class name because we only want the member name.
        classOrIntName = classOrIntName.indexOf('.') != 0
                ? classOrIntName.substring(classOrIntName.lastIndexOf('.'))
                : classOrIntName;
        return "clint" + classOrIntName;
    }
}
 
Example 18
Project: GankReader   File: OnceClickProcessor.java   View source code 6 votes vote down vote up
/**
 * 取得方法参数类型列表
 */
private List<String> getMethodParameterTypes(ExecutableElement executableElement) {
    List<? extends VariableElement> methodParameters = executableElement.getParameters();
    if (methodParameters.size() == 0) {
        return null;
    }
    List<String> types = new ArrayList<>();
    for (VariableElement variableElement : methodParameters) {
        TypeMirror methodParameterType = variableElement.asType();
        if (methodParameterType instanceof TypeVariable) {
            TypeVariable typeVariable = (TypeVariable) methodParameterType;
            methodParameterType = typeVariable.getUpperBound();
        }
        types.add(methodParameterType.toString());
    }
    return types;
}
 
Example 19
Project: GitHub   File: RequestOptionsGenerator.java   View source code 6 votes vote down vote up
private boolean isMethodInRequestOptions(ExecutableElement toFind) {
  // toFind is a method in a GlideExtension whose first argument is a BaseRequestOptions<?> type.
  // Since we're comparing against methods in BaseRequestOptions itself, we need to drop that
  // first type.
  List<String> toFindParameterNames = getComparableParameterNames(toFind, true /*skipFirst*/);
  String toFindSimpleName = toFind.getSimpleName().toString();
  for (Element element : requestOptionsType.getEnclosedElements()) {
    if (element.getKind() != ElementKind.METHOD) {
      continue;
    }
    ExecutableElement inBase = (ExecutableElement) element;
    if (toFindSimpleName.equals(inBase.getSimpleName().toString())) {
      List<String> parameterNamesInBase =
          getComparableParameterNames(inBase, false /*skipFirst*/);
      if (parameterNamesInBase.equals(toFindParameterNames)) {
        return true;
      }
    }
  }
  return false;
}
 
Example 20
Project: openjdk-jdk10   File: Utils.java   View source code 6 votes vote down vote up
/**
 * Return true if the given Element is deprecated for removal.
 *
 * @param e the Element to check.
 * @return true if the given Element is deprecated for removal.
 */
public boolean isDeprecatedForRemoval(Element e) {
    List<? extends AnnotationMirror> annotationList = e.getAnnotationMirrors();
    JavacTypes jctypes = ((DocEnvImpl) configuration.docEnv).toolEnv.typeutils;
    for (AnnotationMirror anno : annotationList) {
        if (jctypes.isSameType(anno.getAnnotationType().asElement().asType(), getDeprecatedType())) {
            Map<? extends ExecutableElement, ? extends AnnotationValue> pairs = anno.getElementValues();
            if (!pairs.isEmpty()) {
                for (ExecutableElement element : pairs.keySet()) {
                    if (element.getSimpleName().contentEquals("forRemoval")) {
                        return Boolean.parseBoolean((pairs.get(element)).toString());
                    }
                }
            }
        }
    }
    return false;
}
 
Example 21
Project: incubator-netbeans   File: ElementUtilitiesEx.java   View source code 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 22
Project: incubator-netbeans   File: ReplaceBufferByString.java   View source code 6 votes vote down vote up
private ExpressionTree rewriteNewClass(TreePath p) {
    ExpressionTree expr = (ExpressionTree) p.getLeaf();
    NewClassTree nct = (NewClassTree) expr;
    Element el = wc.getTrees().getElement(p);
    if (el != null && el.getKind() == ElementKind.CONSTRUCTOR) {
        ExecutableElement ee = (ExecutableElement) el;
        if (ee.getParameters().isEmpty()) {
            // ctor without parameters, remove
            return null;
        }
        TypeMirror argType = ee.getParameters().get(0).asType();
        if (argType.getKind() == TypeKind.DECLARED) {
            ExpressionTree a = nct.getArguments().get(0);
            gu.copyComments(expr, a, true);
            gu.copyComments(expr, a, false);
            wc.rewrite(expr, a);
            return a;
        }
        return null;
    }
    return expr;
}
 
Example 23
Project: incubator-netbeans   File: ElementUtilities.java   View source code 5 votes vote down vote up
@Override
public StringBuilder visitExecutable(ExecutableElement e, Boolean p) {
    if (p != Boolean.TRUE || e.getEnclosingElement() == null) {
        return DEFAULT_VALUE.append(e.getSimpleName());
    } else {
        return e.getEnclosingElement().accept(this, p).
            append(".").
            append(e.getSimpleName());
    }
}
 
Example 24
Project: incubator-netbeans   File: ElementJavadoc.java   View source code 5 votes vote down vote up
private Integer getIdx(Element e, Name n) {
    if (e instanceof ExecutableElement && n != null) {
        int idx = 0;
        for (VariableElement par : ((ExecutableElement)e).getParameters()) {
            if (n.contentEquals(par.getSimpleName())) {
                return idx;
            }
            idx++;
        }
    }
    return null;
}
 
Example 25
Project: incubator-netbeans   File: TestMethodNameGenerator.java   View source code 5 votes vote down vote up
/**
 * Collects names of accessible no-argument methods that are present
 * in the given class and its superclasses. Methods inherited from the
 * class's superclasses are taken into account, too.
 * 
 * @param  clazz  class whose methods' names should be collected
 * @param  reservedMethodNames  collection to which the method names
 *                              should be added
 */
private void collectExistingMethodNames(TypeElement clazz,
                                        Collection<String> reservedMethodNames) {
    final Elements elements = workingCopy.getElements();
    List<? extends Element> allMembers = elements.getAllMembers(clazz);
    List<? extends ExecutableElement> methods = ElementFilter.methodsIn(allMembers);
    if (!methods.isEmpty()) {
        for (ExecutableElement method : methods) {
            if (method.getParameters().isEmpty()) {
                reservedMethodNames.add(method.getSimpleName().toString());
            }
        }
    }
}
 
Example 26
Project: arez   File: MethodChecks.java   View source code 5 votes vote down vote up
private static void mustNotBeStatic( @Nonnull final String annotationName,
                                     @Nonnull final ExecutableElement method )
  throws ArezProcessorException
{
  if ( method.getModifiers().contains( Modifier.STATIC ) )
  {
    throw new ArezProcessorException( "@" + ProcessorUtil.toSimpleName( annotationName ) + " target must not be static", method );
  }
}
 
Example 27
Project: react4j   File: EventHandlerDescriptor.java   View source code 5 votes vote down vote up
EventHandlerDescriptor( @Nonnull final String name,
                        @Nonnull final ExecutableElement method,
                        @Nonnull final ExecutableType methodType,
                        @Nonnull final TypeElement eventHandlerType,
                        @Nonnull final ExecutableElement eventHandlerMethod )
{
  _name = Objects.requireNonNull( name );
  _method = Objects.requireNonNull( method );
  _methodType = Objects.requireNonNull( methodType );
  _eventHandlerType = Objects.requireNonNull( eventHandlerType );
  _eventHandlerMethod = Objects.requireNonNull( eventHandlerMethod );
}
 
Example 28
Project: auto-adapter   File: Util.java   View source code 5 votes vote down vote up
/**
 * Returns the no-args constructor for {@code type}, or null if no such constructor exists.
 */
static ExecutableElement getNoArgsConstructor(final Element type) {
    for (Element enclosed : type.getEnclosedElements()) {
        if (enclosed.getKind() != ElementKind.CONSTRUCTOR) {
            continue;
        }

        ExecutableElement constructor = (ExecutableElement) enclosed;
        if (constructor.getParameters().isEmpty()) {
            return constructor;
        }
    }

    return null;
}
 
Example 29
Project: incubator-netbeans   File: JpaControllerUtil.java   View source code 5 votes vote down vote up
/**
 * TODO: actually it's guess setter from setter, need to review if it's a problem of expected
 * @param setter
 * @return 
 */
public static VariableElement guessGetter(ExecutableElement setter) {
    String name = setter.getSimpleName().toString().substring(3);
    String guessGetterName = "set" + name;
    TypeElement typeElement = (TypeElement) setter.getEnclosingElement();
    for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
        if (variableElement.getSimpleName().contentEquals(guessGetterName)) {
            return variableElement;
        }
    }
    Logger.getLogger(JpaControllerUtil.class.getName()).log(Level.INFO, "Cannot detect setter associated with getter: {0}", guessGetterName);
    return null;
}
 
Example 30
Project: openjdk-jdk10   File: ApNavigator.java   View source code 5 votes vote down vote up
public boolean hasDefaultConstructor(TypeElement t) {
    if (t == null || !t.getKind().equals(ElementKind.CLASS))
        return false;

    for (ExecutableElement init : ElementFilter.constructorsIn(env.getElementUtils().getAllMembers(t))) {
        if (init.getParameters().isEmpty())
            return true;
    }
    return false;
}
 
Example 31
Project: react4j   File: ComponentDescriptor.java   View source code 5 votes vote down vote up
void setLifecycleMethods( @Nonnull final List<MethodDescriptor> lifecycleMethods )
{
  _lifecycleMethods = Objects.requireNonNull( lifecycleMethods );
  for ( final MethodDescriptor method : _lifecycleMethods )
  {
    final ExecutableElement m = method.getMethod();
    if ( null != ProcessorUtil.findAnnotationByType( m, Constants.EVENT_HANDLER_ANNOTATION_CLASSNAME ) )
    {
      throw new ReactProcessorException( "@EventHandler target must not be a lifecycle method", m );
    }
  }
}
 
Example 32
Project: openjdk-jdk10   File: SourceCodeAnalysisImpl.java   View source code 5 votes vote down vote up
private Stream<TypeMirror> parameterType(ExecutableElement method, ExecutableType methodType, int paramIndex, boolean allowVarArgsArray) {
    int paramCount = methodType.getParameterTypes().size();
    if (paramIndex >= paramCount && !method.isVarArgs())
        return Stream.empty();
    if (paramIndex < paramCount - 1 || !method.isVarArgs())
        return Stream.of(methodType.getParameterTypes().get(paramIndex));
    TypeMirror varargType = methodType.getParameterTypes().get(paramCount - 1);
    TypeMirror elemenType = ((ArrayType) varargType).getComponentType();
    if (paramIndex >= paramCount || !allowVarArgsArray)
        return Stream.of(elemenType);
    return Stream.of(varargType, elemenType);
}
 
Example 33
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
public static ExecutableElement[] getMethod(TypeElement clazz, String methodName) {
    List<ExecutableElement> methods = new ArrayList<ExecutableElement>();

    for (ExecutableElement method : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
        if (method.getSimpleName().contentEquals(methodName)) {
            methods.add(method);
        }
    }

    return methods.toArray(new ExecutableElement[methods.size()]);
}
 
Example 34
Project: GitHub   File: ValueType.java   View source code 5 votes vote down vote up
public Set<String> getNonAttributeAbstractMethodSignatures() {
  if (element.getKind().isClass() || element.getKind().isInterface()) {
    Set<String> signatures = new LinkedHashSet<>();

    List<? extends Element> members = constitution.protoclass()
        .environment()
        .processing()
        .getElementUtils()
        .getAllMembers(CachingElements.getDelegate((TypeElement) element));

    for (ExecutableElement m : ElementFilter.methodsIn(members)) {
      if (!m.getParameters().isEmpty()
          || m.getSimpleName().contentEquals(AccessorAttributesCollector.HASH_CODE_METHOD)
          || m.getSimpleName().contentEquals(AccessorAttributesCollector.TO_STRING_METHOD)) {

        if (m.getModifiers().contains(Modifier.ABSTRACT)) {
          TypeMirror returnType = m.getReturnType();
          if (!AccessorAttributesCollector.isEclipseImplementation(m)) {
            returnType = AccessorAttributesCollector.asInheritedMemberReturnType(
                constitution.protoclass().processing(),
                CachingElements.getDelegate((TypeElement) element),
                m);
          }
          signatures.add(toSignature(m, returnType));
        }
      }
    }

    return signatures;
  }
  return Collections.emptySet();
}
 
Example 35
Project: ThreadGeny-master   File: ViewInjectProcess.java   View source code 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {

    try {
        Map<TypeElement, List<ExecutableElement>> tmap = handleTypeAnnotation(roundEnvironment);
        writeJavaClassWithTypeMap(tmap);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 36
Project: openjdk-jdk10   File: WebServiceVisitor.java   View source code 5 votes vote down vote up
protected VariableElement getOutParameter(ExecutableElement method) {
    WebParam webParam;
    for (VariableElement param : method.getParameters()) {
        webParam = param.getAnnotation(WebParam.class);
        if (webParam != null && webParam.mode() != WebParam.Mode.IN) {
            return param;
        }
    }
    return null;
}
 
Example 37
Project: incubator-netbeans   File: AbstractTestGenerator.java   View source code 5 votes vote down vote up
/**
 * Checks whether there is an instance (non-static) method among the given
 * methods.
 * 
 * @param  methods  methods to probe
 * @return  {@literal true} if there is at least one non-static method in the
 *          given list of methods, {@literal false} otherwise
 */
private static boolean hasInstanceMethods(List<ExecutableElement> methods) {
    if (methods.isEmpty()) {
        return false;
    }

    for (ExecutableElement method : methods) {
        if (!method.getModifiers().contains(STATIC)) {
            return true;
        }
    }
    return false;
}
 
Example 38
Project: arez   File: ProcessorUtil.java   View source code 5 votes vote down vote up
static void copyAccessModifiers( @Nonnull final ExecutableElement element, @Nonnull final MethodSpec.Builder builder )
{
  if ( element.getModifiers().contains( Modifier.PUBLIC ) )
  {
    builder.addModifiers( Modifier.PUBLIC );
  }
  else if ( element.getModifiers().contains( Modifier.PROTECTED ) )
  {
    builder.addModifiers( Modifier.PROTECTED );
  }
}
 
Example 39
Project: openjdk-jdk10   File: VisibleMemberMap.java   View source code 5 votes vote down vote up
/**
 * Filter the annotation type members and return either the required
 * members or the optional members, depending on the value of the
 * required parameter.
 *
 * @param typeElement The annotation type to process.
 * @param required
 * @return the annotation type members and return either the required
 * members or the optional members, depending on the value of the
 * required parameter.
 */
private List<Element> filterAnnotations(TypeElement typeElement, boolean required) {
    List<Element> members = utils.getAnnotationMethods(typeElement);
    List<Element> targetMembers = new ArrayList<>();
    for (Element member : members) {
        ExecutableElement ee = (ExecutableElement)member;
        if ((required && ee.getDefaultValue() == null)
                || ((!required) && ee.getDefaultValue() != null)) {
            targetMembers.add(member);
        }
    }
    return targetMembers;
}
 
Example 40
Project: incubator-netbeans   File: JavadocCompletionItem.java   View source code 5 votes vote down vote up
public static CompletionItem createExecutableItem(CompilationInfo info, ExecutableElement e,
        ExecutableType et, int startOffset, boolean isInherited,
        boolean isDeprecated) {
    
    CompletionItem delegate = JavaCompletionItem.createExecutableItem(
            info, e, et, null, startOffset, null, isInherited, isDeprecated, false, false, false, -1, false, null);
    return new JavadocExecutableItem(delegate, e, startOffset);
}