Java Code Examples for javax.lang.model.element.ElementKind#CONSTRUCTOR

The following examples show how to use javax.lang.model.element.ElementKind#CONSTRUCTOR . 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: ElementGrip.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ElementGrip(TreePathHandle delegateElementHandle, Element elm, CompilationInfo info) {
        this.delegateElementHandle = delegateElementHandle;
        this.handle = elm == null ? null : ElementHandle.create(elm);
        if (elm != null) {
            if (elm.getKind() == ElementKind.CLASS && elm.getSimpleName().length() == 0) {
                this.toString = ((TypeElement) elm).asType().toString();
                this.icon = ElementIcons.getElementIcon(elm.getKind(), elm.getModifiers());
            } else if(elm.getKind() == ElementKind.ENUM 
                    && elm.getSimpleName().length() == 0
                    && elm.getEnclosingElement() != null) {
                final Element enclosingElement = elm.getEnclosingElement();
                this.toString = enclosingElement.getSimpleName().toString();
                this.icon = ElementIcons.getElementIcon(enclosingElement.getKind(), enclosingElement.getModifiers());
            } else {
                // workaround for issue 171692
                this.toString = elm.getKind() != ElementKind.CONSTRUCTOR
                        ? elm.getSimpleName().toString()
                        : elm.getEnclosingElement().getSimpleName().toString();
                this.icon = ElementIcons.getElementIcon(elm.getKind(), elm.getModifiers());
//            this.toString = ElementHeaders.getHeader(treePath, info, ElementHeaders.NAME);
            }
        }
        this.fileObject = info.getFileObject();
    }
 
Example 2
Source File: MemberInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static <T extends Element> MemberInfo<ElementHandle<T>> create(T el, CompilationInfo c) {
    String format = ElementHeaders.NAME;
    Group g = Group.TYPE;
    if (el.getKind() == ElementKind.FIELD) {
        format += " : " + ElementHeaders.TYPE; // NOI18N
        g=Group.FIELD;
    } else if (el.getKind() == ElementKind.METHOD) {
        format += ElementHeaders.PARAMETERS + " : " + ElementHeaders.TYPE; // NOI18N
        g=Group.METHOD;
    } else if (el.getKind() == ElementKind.CONSTRUCTOR) {
        format += ElementHeaders.PARAMETERS;
        g=Group.METHOD;
    } 

    MemberInfo<ElementHandle<T>> mi = new MemberInfo<ElementHandle<T>>(ElementHandle.create(el), el.getSimpleName().toString(), ElementHeaders.getHeader(el, c, format), ElementIcons.getElementIcon(el.getKind(), el.getModifiers()));
    mi.modifiers = el.getModifiers();
    mi.group = g;
    return mi;
}
 
Example 3
Source File: PathExtractor.java    From Mortar-architect with MIT License 6 votes vote down vote up
@Override
public void extract() {
    if (element.getKind() != ElementKind.CLASS) {
        errors.addInvalid("Annotation can be applied only on a class");
        return;
    }

    viewTypeMirror = ExtractorUtils.getValueFromAnnotation(element, AutoPath.class, ANNOTATION_VIEW);
    if (viewTypeMirror == null) {
        errors.addMissing("withView() value");
    }

    constructorElements = new ArrayList<>();
    for (Element e : element.getEnclosedElements()) {
        if (e.getKind() == ElementKind.CONSTRUCTOR) {
            constructorElements.add(MoreElements.asExecutable(e));
        }
    }
}
 
Example 4
Source File: JavadocImports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Element paramElementFor(Element methodOrClass, ParamTree ptag) {
    ElementKind kind = methodOrClass.getKind();
    List<? extends Element> params = Collections.emptyList();
    if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
        ExecutableElement ee = (ExecutableElement) methodOrClass;
        params = ptag.isTypeParameter()
                ? ee.getTypeParameters()
                : ee.getParameters();
    } else if (kind.isClass() || kind.isInterface()) {
        TypeElement te = (TypeElement) methodOrClass;
        params = te.getTypeParameters();
    }

    for (Element param : params) {
        if (param.getSimpleName().contentEquals(ptag.getName().getName())) {
            return param;
        }
    }
    return null;
}
 
Example 5
Source File: JavacTrees.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
    Symbol javadocSymbol = getElement(path);
    if (javadocSymbol == null)
        return null;
    ElementKind kind = javadocSymbol.getKind();
    List<? extends Symbol> params = List.nil();
    if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
        MethodSymbol ee = (MethodSymbol) javadocSymbol;
        params = ptag.isTypeParameter()
                ? ee.getTypeParameters()
                : ee.getParameters();
    } else if (kind.isClass() || kind.isInterface()) {
        ClassSymbol te = (ClassSymbol) javadocSymbol;
        params = te.getTypeParameters();
    }

    for (Symbol param : params) {
        if (param.getSimpleName() == ptag.getName().getName()) {
            return param;
        }
    }
    return null;
}
 
Example 6
Source File: GeneratedClassMapperProcessor.java    From pandroid with Apache License 2.0 6 votes vote down vote up
@Override
public CodeBlock toCodeBlock(TypeName parentType) {
    CodeBlock.Builder code = CodeBlock.builder();

    for (Element enclosed : typeElement.getEnclosedElements()) {
        if (enclosed.getKind() == ElementKind.CONSTRUCTOR) {
            ExecutableElement constructorElement = (ExecutableElement) enclosed;
            if (constructorElement.getModifiers().contains(Modifier.PUBLIC)) {
                if (constructorElement.getParameters().size() == 0) {
                    code.addStatement("result.add((T)new $T())", typeElement);
                    break;
                } else if (constructorElement.getParameters().size() == 1) {
                    code.addStatement("result.add((T)new $T(($T)$L))", typeElement, type, TARGET_VAR_NAME);
                    break;
                }
            }
        }
    }

    code.add(childs.toCodeBlock(TARGET_VAR_NAME, parentType));

    return code.build();
}
 
Example 7
Source File: JavacTrees.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
    Symbol javadocSymbol = getElement(path);
    if (javadocSymbol == null)
        return null;
    ElementKind kind = javadocSymbol.getKind();
    List<? extends Symbol> params = List.nil();
    if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
        MethodSymbol ee = (MethodSymbol) javadocSymbol;
        params = ptag.isTypeParameter()
                ? ee.getTypeParameters()
                : ee.getParameters();
    } else if (kind.isClass() || kind.isInterface()) {
        ClassSymbol te = (ClassSymbol) javadocSymbol;
        params = te.getTypeParameters();
    }

    for (Symbol param : params) {
        if (param.getSimpleName() == ptag.getName().getName()) {
            return param;
        }
    }
    return null;
}
 
Example 8
Source File: SemanticHighlighterBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 9
Source File: ReplaceConstructorWithFactoryPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected Problem preCheck(CompilationController javac) throws IOException {
    javac.toPhase(JavaSource.Phase.RESOLVED);
    Element constr = treePathHandle.resolveElement(javac);
    if(constr.getKind() != ElementKind.CONSTRUCTOR) {
        return new Problem(true, ERR_ReplaceWrongType());
    }
    Element enclosingElement = constr.getEnclosingElement();
    if(!enclosingElement.getModifiers().contains(Modifier.STATIC) && enclosingElement.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        return new Problem(true, ERR_ReplaceWrongInnerType());
    }
    return null;
}
 
Example 10
Source File: WhiteListSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void handleNode(
        final Tree node,
        final Map<Tree,WhiteListQuery.Result> p) {
    final Element e = trees.getElement(getCurrentPath());
    if (e == null) {
        return;
    }
    final ElementKind k = e.getKind();
    ElementHandle<?> eh = null;
    Tree toReport =  null;
    if (k.isClass() || k.isInterface()) {
        TypeMirror type = e.asType();
        if (type != null) {
            type = findComponentType(type);
            if (type.getKind() == TypeKind.DECLARED) {
                eh = ElementHandle.create(((DeclaredType)type).asElement());
                toReport=node;
            }
        }
    } else if ((k == ElementKind.METHOD || k == ElementKind.CONSTRUCTOR) &&
            !methodInvocation.isEmpty()) {
        toReport=methodInvocation.peekFirst();
        eh = ElementHandle.create(e);
    }
    final WhiteListQuery.Result res;
    if (toReport != null &&
        !(res=whiteList.check(eh,WhiteListQuery.Operation.USAGE)).isAllowed()) {
            p.put(toReport,res);
    }
}
 
Example 11
Source File: Proto.java    From immutables with Apache License 2.0 5 votes vote down vote up
TypeNames createTypeNames() {
  Element sourceElement = sourceElement();
  if (sourceElement.getKind() == ElementKind.CONSTRUCTOR) {
    sourceElement = sourceElement.getEnclosingElement();
  }
  return styles().forType(sourceElement.getSimpleName().toString());
}
 
Example 12
Source File: Symbol.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    if (name == name.table.names.init)
        return ElementKind.CONSTRUCTOR;
    else if (name == name.table.names.clinit)
        return ElementKind.STATIC_INIT;
    else if ((flags() & BLOCK) != 0)
        return isStatic() ? ElementKind.STATIC_INIT : ElementKind.INSTANCE_INIT;
    else
        return ElementKind.METHOD;
}
 
Example 13
Source File: AttributeBuilderReflection.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Return true if the possibleBuilderMethod matches the
 * Style#attributeBuilder() and returns a class.
 *
 * TODO: may need to make this return true if the return type is an interface too...
 *
 * @param possibleBuilderMethod executableElement
 */
private static boolean isPossibleBuilderMethod(Element possibleBuilderMethod, boolean onValueType, ValueAttribute valueAttribute) {
  if (possibleBuilderMethod.getKind() == ElementKind.METHOD) {
    if (!valueAttribute.containingType.names().possibleAttributeBuilder(possibleBuilderMethod.getSimpleName())) {
      return false;
    }

    ExecutableElement candidateMethod = (ExecutableElement) possibleBuilderMethod;

    TypeKind kind = candidateMethod.getReturnType().getKind();

    return possibleBuilderMethod.getModifiers().containsAll(
        Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))
        && candidateMethod.getParameters().isEmpty()
        && candidateMethod.getReturnType().getKind() == TypeKind.DECLARED
        && !kind.isPrimitive() && kind != TypeKind.ARRAY;

  } else if (!onValueType && possibleBuilderMethod.getKind() == ElementKind.CONSTRUCTOR) {
    if (!valueAttribute.containingType.names().newTokenInAttributeBuilder()) {
      return false;
    }

    ExecutableElement candidateConstructor = (ExecutableElement) possibleBuilderMethod;

    return candidateConstructor.getModifiers().contains(Modifier.PUBLIC)
        && candidateConstructor.getTypeParameters().isEmpty();
  }
  return false;
}
 
Example 14
Source File: Symbol.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    if (name == name.table.names.init)
        return ElementKind.CONSTRUCTOR;
    else if (name == name.table.names.clinit)
        return ElementKind.STATIC_INIT;
    else if ((flags() & BLOCK) != 0)
        return isStatic() ? ElementKind.STATIC_INIT : ElementKind.INSTANCE_INIT;
    else
        return ElementKind.METHOD;
}
 
Example 15
Source File: ActivityPageProcess.java    From stitch with Apache License 2.0 5 votes vote down vote up
private void processConstruct(List<? extends Element> enclosedElements) {
    for (Element e : enclosedElements) {
        if (e.getKind() == ElementKind.CONSTRUCTOR && e.getModifiers().contains(Modifier.PUBLIC)) {
            ExecutableElement executableElement = (ExecutableElement) e;
            ConstructorBinding constructorBinding = new ConstructorBinding();
            constructorBinding.className = activityPageBinding.activityPageClass;
            int size = executableElement.getParameters().size();
            constructorBinding.parametersType = new String[size];
            constructorBinding.parametersName = new String[size];
            for (int i = 0; i < size; i++) {
                VariableElement p = executableElement.getParameters().get(i);
                String type = p.asType().toString();
                if (!activityPageBinding.imports.containsKey(type)) {
                    TypeElement el = environment.getElementUtils().getTypeElement(type);
                    if (el != null) {
                        activityPageBinding.imports.put(type, el.getSimpleName().toString());
                    }
                }
                if (activityPageBinding.imports.containsKey(type)) {
                    type = activityPageBinding.imports.get(type);
                }
                constructorBinding.parametersType[i] = type;
                constructorBinding.parametersName[i] = p.getSimpleName().toString();
            }
            activityPageBinding.constructors.add(constructorBinding);
        }
    }
    if (activityPageBinding.constructors.size() == 0) {
        throw new IllegalStateException(element.getQualifiedName() + " need at least 1 PUBLIC Constructor.");
    }
}
 
Example 16
Source File: TreeUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static boolean isConstructor(CompilationInfo info, TreePath path) {
    Element e = info.getTrees().getElement(path);
    return e != null && e.getKind() == ElementKind.CONSTRUCTOR;
}
 
Example 17
Source File: WhiteListImplementationBuilder.java    From netbeans with Apache License 2.0 4 votes vote down vote up
boolean isAllowed(
        @NonNull final ElementHandle<?> element,
        final byte mode) {
    final String[] vmSignatures = SourceUtils.getJVMSignature(element);
    final String[] pkgNamePair = splitName(vmSignatures[0],'.');  //NOI18N
    
    if (isThere(allowedPackages, pkgNamePair[0])) {
        return true;
    }
    if (isThere(disallowedPackages, pkgNamePair[0])) {
        return false;
    }
    
    if (!checkedPkgs.second().matcher(pkgNamePair[0]+'.').matches()) {  //NOI18N
        return true;
    }
    final Integer pkgId = names.getName(pkgNamePair[0]);
    final Integer clsId = names.getName(pkgNamePair[1]);
    final IntermediateCacheNode<IntermediateCacheNode<IntermediateCacheNode<CacheNode>>> pkgNode = root.get(pkgId);
    if (pkgNode == null) {
        return false;
    }
    final IntermediateCacheNode<IntermediateCacheNode<CacheNode>> clsNode = pkgNode.get(clsId);
    if (clsNode == null) {
        return false;
    }
    if ((clsNode.state & mode) == mode) {
        return true;
    }
    if (element.getKind() == ElementKind.METHOD ||
        element.getKind() == ElementKind.CONSTRUCTOR) {
        final Integer methodNameId = names.getName(vmSignatures[1]);
        final Integer methodSigId = names.getName(paramsOnly(vmSignatures[2]));
        final IntermediateCacheNode<CacheNode> methodNameNode = clsNode.get(methodNameId);
        if (methodNameNode == null) {
            return false;
        }
        final CacheNode methodSigNode = methodNameNode.get(methodSigId);
        if (methodSigNode == null) {
            return false;
        }
        return (methodSigNode.state & mode) == mode;
    } else if ((element.getKind().isClass() ||
        element.getKind().isInterface()) && clsNode.hasChildren()) {
        //If the request is for type and it has at least one alowed method
        //allow it. It would be strange to black list type usage which method is allowed
        return true;
    }
    return false;
}
 
Example 18
Source File: ActionProcessor.java    From netbeans with 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 19
Source File: Bundler.java    From easybundler with Apache License 2.0 4 votes vote down vote up
/**
 * Create the "fromBundle" method that accepts a Bundle and returns a member
 * of the wrapped class.
 */
private MethodSpec createFromBundleMethod() {
    MethodSpec.Builder builder = MethodSpec.methodBuilder("fromBundle")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(BUNDLE_CLASS, "bundle")
            .returns(info.className);

    // Ensure the class has an empty constructor
    boolean hasEmptyConstructor = false;
    for (Element e : info.typeElement.getEnclosedElements()) {
        if (e.getKind() == ElementKind.CONSTRUCTOR) {
            boolean isEmptyConstructor = ((ExecutableElement) e).getParameters().isEmpty();
            hasEmptyConstructor = hasEmptyConstructor || isEmptyConstructor;
        }
    }

    if (!hasEmptyConstructor) {
        String message = "[EasyBundler] Type " + info.className
                + " does not have default constructor!";
        environment.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
    }

    // Create a new instance of the object
    builder.addStatement("$T object = new $T()", info.className, info.className);

    // Get each field from the bundle and set it on the object
    for (VariableElement field : getApplicableFields()) {
        // Decide on the key for the field and how to get it from the bundle
        String fieldKey = getFieldKey(field);
        String getMethod = bundleGetMethod(field);

        if (isPublic(field)) {
            // Public fields can be set directly
            // Ex: object.someField = (Type) bundle.getString("KEY")
            if (requiresCast(getMethod)) {
                // Set with cast
                builder.addStatement("object.$L = ($T) bundle.$L($S)",
                        field.getSimpleName(), field.asType(), getMethod, fieldKey);
            } else {
                // Set without cast
                builder.addStatement("object.$L = bundle.$L($S)",
                        field.getSimpleName(), getMethod, fieldKey);
            }
        } else {
            // Non-public fields are set with the setter
            // Ex: object.setSomeField((Type) bundle.getString("KEY"))
            if (requiresCast(getMethod)) {
                // Set with cast
                builder.addStatement("object.$L(($T) bundle.$L($S))",
                        setterName(field), field.asType(), getMethod, fieldKey);
            } else {
                // Set without cast
                builder.addStatement("object.$L(bundle.$L($S))",
                        setterName(field), getMethod, fieldKey);
            }
        }
    }

    // Return the object instance
    builder.addStatement("return object");

    return builder.build();
}
 
Example 20
Source File: PullUpRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected Problem preCheck(CompilationController cc) throws IOException {
    fireProgressListenerStart(AbstractRefactoring.PRE_CHECK, 4);
    try {
        cc.toPhase(JavaSource.Phase.RESOLVED);
        Problem problem = isElementAvail(treePathHandle, cc);
        if (problem != null) {
            // fatal error -> don't continue with further checks
            return problem;
        }

        // increase progress (step 1)
        fireProgressListenerStep();
        final Element elm = treePathHandle.resolveElement(cc);
        problem = JavaPluginUtils.isSourceElement(elm, cc);
        if (problem != null) {
            return problem;
        }
        if (!(elm instanceof TypeElement)) {
            return new Problem(true, NbBundle.getMessage(PushDownRefactoringPlugin.class, "ERR_PushDown_InvalidSource", treePathHandle, elm)); // NOI18N
        }
        TypeElement e  = (TypeElement) elm;
        Collection<TypeElement> superTypes = JavaRefactoringUtils.getSuperTypes(e, cc, true);
        List<MemberInfo> minfo = new LinkedList<MemberInfo>();
        for (TypeElement el: superTypes) {
            MemberInfo<ElementHandle<TypeElement>> memberInfo = MemberInfo.create(el, cc);
            if(memberInfo.getElementHandle().resolve(cc) != null) { // #200200 - Error in pulling up to a interface with cyclic inheritance error
                minfo.add(memberInfo);
            }
        }
        if (minfo.isEmpty()) {
            return new Problem(true, NbBundle.getMessage(PullUpRefactoringPlugin.class, "ERR_PullUp_NoSuperTypes")); // NOI18N
        }
        // increase progress (step 2)
        fireProgressListenerStep();
        // #2 - check if there are any members to pull up
        for (Element element : e.getEnclosedElements()) {
            if (element.getKind() != ElementKind.CONSTRUCTOR) {
                return null;
            }
        }
        if (!e.getInterfaces().isEmpty()) {
            return null;
        }
        problem = new Problem(true, NbBundle.getMessage(PullUpRefactoringPlugin.class, "ERR_PullUp_NoMembers")); // NOI18N
        // increase progress (step 3)
        fireProgressListenerStep();
        return problem;
    } finally {
        fireProgressListenerStop();
    }
}