Java Code Examples for javax.lang.model.element.Element#getModifiers()

The following examples show how to use javax.lang.model.element.Element#getModifiers() . 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: FieldsExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
public static <T extends Element> ImmutableList<FieldModel> extractFields(T element) {
  final List<FieldModel> fields = new ArrayList<>();

  for (Element enclosedElement : element.getEnclosedElements()) {
    if (ElementKind.FIELD.equals(enclosedElement.getKind())) {
      Set<Modifier> modifiers = enclosedElement.getModifiers();
      fields.add(
          new FieldModel(
              FieldSpec.builder(
                      TypeName.get(enclosedElement.asType()),
                      enclosedElement.getSimpleName().toString(),
                      modifiers.toArray(new Modifier[modifiers.size()]))
                  .build(),
              enclosedElement));
    }
  }

  return ImmutableList.copyOf(fields);
}
 
Example 2
Source File: MemberInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static MemberInfo<TreePathHandle> create(TreePath tpath, CompilationInfo c) {
    String format = ElementHeaders.NAME;
    Group g = null;
    Element el = c.getTrees().getElement(tpath);
    if (el == null) {
        return null;
    }
    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().isInterface()) {
        g=Group.IMPLEMENTS;
        format = "implements " + format; // NOI18N
    }

    MemberInfo<TreePathHandle> mi = new MemberInfo<TreePathHandle>(TreePathHandle.create(tpath, c), 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: TypeUtils.java    From Mixin with MIT License 6 votes vote down vote up
/**
 * Get the ordinal visibility for the specified element
 * 
 * @param element element to inspect
 * @return visibility level or null if element is null
 */
public static Visibility getVisibility(Element element) {
    if (element == null) {
        return null;
    }
    
    for (Modifier modifier : element.getModifiers()) {
        switch (modifier) {
            case PUBLIC: return Visibility.PUBLIC;
            case PROTECTED: return Visibility.PROTECTED;
            case PRIVATE: return Visibility.PRIVATE;
            default: break;
        }
    }
    
    return Visibility.PACKAGE;
}
 
Example 4
Source File: BindingProcessor.java    From pocketknife with Apache License 2.0 6 votes vote down vote up
protected Access getAccess(Class<? extends Annotation> annotationClass, Element element, TypeElement enclosingElement) {
    Set<Modifier> modifiers = element.getModifiers();
    if (modifiers.contains(PROTECTED) || modifiers.contains(PRIVATE)) {
        String getter = findGetter(element);
        String setter = findSetter(element);
        if (getter == null || setter == null) {
            throw new IllegalStateException(String.format("@%s fields must have a Java Bean getter and a setter if it is private or protected. (%s.%s)",
                    annotationClass.getSimpleName(), enclosingElement.getQualifiedName(),
                    element.getSimpleName()));
        }
        return new Access(Access.Type.METHOD, getter, setter);
    }
    String name = element.getSimpleName().toString();
    return new Access(Access.Type.FIELD, name, name);

}
 
Example 5
Source File: Processor.java    From reflection-no-reflection with Apache License 2.0 6 votes vote down vote up
private void addFieldToAnnotationDatabase(Element fieldElement, int level) {
    Class fieldClass;
    //System.out.printf("Type: %s, injection: %s \n",typeElementName, fieldName);
    fieldClass = createClass(fieldElement.asType(), level);

    final Set<Modifier> modifiers = fieldElement.getModifiers();
    String fieldName = fieldElement.getSimpleName().toString();
    TypeElement declaringClassElement = (TypeElement) fieldElement.getEnclosingElement();
    String declaringClassName = declaringClassElement.getQualifiedName().toString();
    final List<Annotation> annotations = extractAnnotations(fieldElement, level);
    int modifiersInt = convertModifiersFromAnnotationProcessing(modifiers);
    final Class<?> enclosingClass = Class.forNameSafe(declaringClassName, level + 1);
    if (level == 0) {
        final Class<? extends Annotation> annotationType = annotations.get(0).rnrAnnotationType();
        Set<Class<?>> classes = mapAnnotationTypeToClassContainingAnnotation.get(annotationType);
        if (classes == null) {
            classes = new HashSet<>();
        }
        classes.add(enclosingClass);
        mapAnnotationTypeToClassContainingAnnotation.put(annotationType, classes);
    }
    final Field field = new Field(fieldName, fieldClass, enclosingClass, modifiersInt, annotations);
    enclosingClass.addField(field);
    annotatedClassSet.add(enclosingClass);
}
 
Example 6
Source File: BeanInstaller.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String isDeclaredAsJavaBean(TypeElement clazz) {
    if (ElementKind.CLASS != clazz.getKind()) {
        return PaletteUtils.getBundleString("MSG_notAClass"); // NOI18N
    }

    Set<javax.lang.model.element.Modifier> mods = clazz.getModifiers();
    if (mods.contains(javax.lang.model.element.Modifier.ABSTRACT)) {
        return PaletteUtils.getBundleString("MSG_abstractClass"); // NOI18N
    }

    if (!mods.contains(javax.lang.model.element.Modifier.PUBLIC)) {
        return PaletteUtils.getBundleString("MSG_notPublic"); // NOI18N
    }
    
    for (Element member : clazz.getEnclosedElements()) {
        mods = member.getModifiers();
        if (ElementKind.CONSTRUCTOR == member.getKind() &&
                mods.contains(javax.lang.model.element.Modifier.PUBLIC) &&
                ((ExecutableElement) member).getParameters().isEmpty()) {
            return null;
        }
    }
    
    return PaletteUtils.getBundleString("MSG_noPublicConstructor"); // NOI18N
}
 
Example 7
Source File: ScopedBeanAnalyzer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkFinal( Element element, WebBeansModel model,
        Result result )
{
    if ( !( element instanceof TypeElement )){
        return;
    }
    Set<Modifier> modifiers = element.getModifiers();
    if ( modifiers.contains( Modifier.FINAL) ){
        result.addError( element, model,  
                NbBundle.getMessage(ScopedBeanAnalyzer.class, 
                        "ERR_FinalScopedClass"));
        return;
    }
    List<ExecutableElement> methods = ElementFilter.methodsIn(
            element.getEnclosedElements());
    for (ExecutableElement method : methods) {
        modifiers = method.getModifiers();
        if (modifiers.contains(Modifier.FINAL)) {
            result.addNotification( Severity.WARNING, method, model, 
                            NbBundle.getMessage(
                            ScopedBeanAnalyzer.class,
                            "WARN_FinalScopedClassMethod"));
        }
    }
}
 
Example 8
Source File: CheckSums.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getExtendedModifiers(Elements elements, Element el) {
    StringBuilder sb = new StringBuilder();
    for (Modifier m : el.getModifiers())
        sb.append(m.name());
    if (elements.isDeprecated(el))
        sb.append(DEPRECATED);
    if (el.getKind() == ElementKind.FIELD) {
        Object v = ((VariableElement) el).getConstantValue();
        if (v != null) {
            sb.append(v.getClass().getName());
            sb.append(String.valueOf(v));
        }
    }
    return sb.toString();
}
 
Example 9
Source File: PreferenceBinderProcessor.java    From preferencebinder with Apache License 2.0 5 votes vote down vote up
private boolean isAccessibleAndStatic(Class<? extends Annotation> annotationClass, Element element){
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify method modifiers.
    Set<Modifier> modifiers = element.getModifiers();
    if (!modifiers.contains(PUBLIC) || !modifiers.contains(STATIC)) {
        error(element, "@%s annotated elements must have public and static modifiers. (%s.%s)",
                annotationClass.getSimpleName(), enclosingElement.getQualifiedName(),
                element.getSimpleName());
        hasError = true;
    }

    // Verify containing type.
    if (enclosingElement.getKind() != CLASS) {
        error(enclosingElement, "@%s annotated elements may only be contained in classes. (%s.%s)",
                annotationClass.getSimpleName(), enclosingElement.getQualifiedName(),
                element.getSimpleName());
        hasError = true;
    }

    // Verify containing class visibility is not private.
    if (enclosingElement.getModifiers().contains(PRIVATE)) {
        error(enclosingElement, "@%s annotated elements may not be contained in private classes. (%s.%s)",
                annotationClass.getSimpleName(), enclosingElement.getQualifiedName(),
                element.getSimpleName());
        hasError = true;
    }

    return hasError;
}
 
Example 10
Source File: OnActivityResultProcessor.java    From OnActivityResult with Apache License 2.0 5 votes vote down vote up
private void checkModifiers(final Element element, final Class<? extends Annotation> annotation, final String scope, final Modifier... modifiers) throws OnActivityResultProcessingException {
    final Set<Modifier> elementModifiers = element.getModifiers();

    for (final Modifier modifier : modifiers) {
        if (elementModifiers.contains(modifier)) {
            throw new OnActivityResultProcessingException(element, "@%s " + scope + " must not be %s", annotation.getSimpleName(), StringUtils.getList(" or ", modifiers));
        }
    }
}
 
Example 11
Source File: Configuration.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
public boolean fieldAllowed(Element element) {
	Set<Modifier> modifiers = element.getModifiers();

	if (!allowTransient() && modifiers.contains(Modifier.TRANSIENT))
		return false;

	if (!allowVolatile() && modifiers.contains(Modifier.VOLATILE))
		return false;

	return true;
}
 
Example 12
Source File: AbstractMemberWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add the modifier for the member. The modifiers are ordered as specified
 * by <em>The Java Language Specification</em>.
 *
 * @param member the member for which teh modifier will be added.
 * @param htmltree the content tree to which the modifier information will be added.
 */
protected void addModifiers(Element member, Content htmltree) {
    Set<Modifier> set = new TreeSet<>(member.getModifiers());

    // remove the ones we really don't need
    set.remove(NATIVE);
    set.remove(SYNCHRONIZED);
    set.remove(STRICTFP);

    // According to JLS, we should not be showing public modifier for
    // interface methods.
    if ((utils.isField(member) || utils.isMethod(member))
        && ((writer instanceof ClassWriterImpl
             && utils.isInterface(((ClassWriterImpl) writer).getTypeElement())  ||
             writer instanceof AnnotationTypeWriterImpl) )) {
        // Remove the implicit abstract and public modifiers
        if (utils.isMethod(member) &&
            (utils.isInterface(member.getEnclosingElement()) ||
             utils.isAnnotationType(member.getEnclosingElement()))) {
            set.remove(ABSTRACT);
            set.remove(PUBLIC);
        }
        if (!utils.isMethod(member)) {
            set.remove(PUBLIC);
        }
    }
    if (!set.isEmpty()) {
        String mods = set.stream().map(Modifier::toString).collect(Collectors.joining(" "));
        htmltree.addContent(mods);
        htmltree.addContent(Contents.SPACE);
    }
}
 
Example 13
Source File: ElementsTable.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if access is allowed.
 *
 * @param e the element in question
 * @return whether the modifiers pass this filter
 */
public boolean checkModifier(Element e) {
    Set<Modifier> modifiers = e.getModifiers();
    AccessKind fflag = AccessKind.PACKAGE;
    if (modifiers.contains(Modifier.PUBLIC)) {
        fflag = AccessKind.PUBLIC;
    } else if (modifiers.contains(Modifier.PROTECTED)) {
        fflag = AccessKind.PROTECTED;
    } else if (modifiers.contains(Modifier.PRIVATE)) {
        fflag = AccessKind.PRIVATE;
    }
    EnumSet<AccessKind> filterSet = filterMap.get(getAllowedKind(e.getKind()));
    return filterSet.contains(fflag);
}
 
Example 14
Source File: ElementNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Description create(CompilationInfo info, Element element, List<Description> subs, boolean isSelectable, boolean isSelected ) {
    boolean deprecated = info.getElements().isDeprecated(element);
    String htmlHeader = null;
    switch (element.getKind()) {
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            htmlHeader = createHtmlHeader(deprecated, (TypeElement)element);
            break;
        case ENUM_CONSTANT:
        case FIELD:
            htmlHeader = createHtmlHeader(deprecated, (VariableElement)element);
            break;
        case CONSTRUCTOR:
        case METHOD:
            htmlHeader = createHtmlHeader(deprecated, (ExecutableElement)element);
            break;                    
    }
    return new Description(element.getSimpleName().toString(), 
                           ElementHandle.create(element), 
                           element.getModifiers(), 
                           subs, 
                           htmlHeader,
                           isSelectable,
                           isSelected);
}
 
Example 15
Source File: ElementDescription.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ElementDescription(CompilationInfo info, Element element, boolean overriddenFlag) {
    this.originalCPInfo = info.getClasspathInfo();
    this.handle = ElementHandle.create(element);
    if (METHOD.equals(element.getKind()) && null != element.getEnclosingElement()) {
        //when showing the implementors/overriders of a method, show the type icon (not the method icon)
        this.imageKind = element.getEnclosingElement().getKind();
    } else {
        this.imageKind = this.handle.getKind();
    }
    this.outtermostElement = ElementHandle.create(SourceUtils.getOutermostEnclosingTypeElement(element));
    this.modifiers = element.getModifiers();
    this.displayName = overriddenFlag ? computeDisplayNameIsOverridden(element) : computeDisplayNameOverrides(element);
    this.overriddenFlag = overriddenFlag;
}
 
Example 16
Source File: ProcessorUtils.java    From Witch-Android with Apache License 2.0 4 votes vote down vote up
private static boolean notPrivateOrProtected(Element e) {
    Set<Modifier> modifiers = e.getModifiers();
    return !modifiers.contains(Modifier.PRIVATE) && !modifiers.contains(Modifier.PROTECTED);
}
 
Example 17
Source File: DataMapProcessor.java    From courier with Apache License 2.0 4 votes vote down vote up
private void writeUnpackImplMethod(StringBuilder builder, TypeElement element, String parentClass) {
    if(parentClass!=null) {
        builder.append(INDENT).append("@Override\n");
    }
    builder.append(INDENT).append("protected void unpack(Context context, DataMap map, T target) {\n");
    if(parentClass!=null) {
        builder.append(INDENT_2).append("super.unpack(context, map, target);\n");
    }

    for(Element subElement:element.getEnclosedElements()) {
        final Set<Modifier> modifiers = subElement.getModifiers();
        final String name = subElement.getSimpleName().toString();

        if(subElement.getKind()==ElementKind.FIELD
                && !modifiers.contains(Modifier.PRIVATE)
                && !modifiers.contains(Modifier.STATIC)
                && !modifiers.contains(Modifier.FINAL)
                ) {

            final DataMapElementType elementType = DataMapElementType.getElementType(subElement);
            if(elementType==null) {
                final String fieldType = subElement.asType().toString();

                if(targetClassNames.contains(fieldType)) {
                    builder.append(INDENT_2).append("target.").append(name).append(" = ");
                    builder.append("Packager.unpack(context, ")
                            .append("map.getDataMap(\"").append(name)
                            .append("\"), ")
                            .append(fieldType).append(".class);\n");
                } else if (fieldType.equals(BITMAP)) {
                    builder.append(INDENT_2).append("final Asset ").append(name).append("Asset = map.getAsset(\"").append(name).append("\");\n");
                    builder.append(INDENT_2).append("if(").append(name).append("Asset!=null && context!=null) {\n");
                    builder.append(INDENT_3).append("final InputStream in = Courier.getAssetInputStream(context, ").append(name).append("Asset);\n");
                    builder.append(INDENT_3).append("target.").append(name).append(" = BitmapFactory.decodeStream(in);\n");
                    builder.append(INDENT_2).append("}\n");
                } else if (fieldType.startsWith("java.util.ArrayList")) {
                    if(fieldType.endsWith(">")) {
                        final String itemType = fieldType.substring(20, fieldType.length() - 1);

                        if(itemType.isEmpty() || itemType.startsWith("?")) {
                            // We need the item type to unpack
                            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Wildcard generic types are not allowed", subElement);
                        } else {
                            builder.append(INDENT_2).append("target.").append(name).append(" = ");
                            builder.append("Packager.unpack(context, ")
                                    .append("map.getDataMapArrayList(\"").append(name)
                                    .append("\"), ")
                                    .append(itemType).append(".class);\n");
                        }
                    } else {
                        // We need the item type to unpack
                        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Generic type must be specified for ArrayLists.", subElement);
                    }
                } else {
                    // Bad field type, show an error linking to this specific element
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Field type not supported ("+fieldType+").", subElement);
                }
            } else {
                builder.append(INDENT_2).append("target.").append(name).append(" = ");
                builder.append("map.").append(elementType.getMethod)
                        .append("(\"").append(name).append("\");\n");
            }
        }
    }

    builder.append(INDENT).append("}\n\n");
}
 
Example 18
Source File: Validator.java    From EasyRouter with Apache License 2.0 4 votes vote down vote up
static Set<Modifier> getModifiers(Element element) {
    return element.getModifiers();
}
 
Example 19
Source File: Validator.java    From EasyMVP with Apache License 2.0 4 votes vote down vote up
static Set<Modifier> getModifiers(Element element) {
    return element.getModifiers();
}
 
Example 20
Source File: OverridableMethodCallInConstructor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Tree.Kind.METHOD_INVOCATION)
public static ErrorDescription hint(HintContext ctx) {
    MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();
    CompilationInfo info = ctx.getInfo();
    TreePath enclosingMethod = Utilities.findOwningExecutable(ctx, ctx.getPath(), false);

    if (enclosingMethod == null) {
        return null;
    }

    Element enclosingMethodElement = ctx.getInfo().getTrees().getElement(enclosingMethod);
    
    if (enclosingMethodElement == null || enclosingMethodElement.getKind() != ElementKind.CONSTRUCTOR) {
        return null;
    }

    Element methodInvocationElement = info.getTrees().getElement(new TreePath(ctx.getPath(), mit.getMethodSelect()));
    if (methodInvocationElement == null || methodInvocationElement.getKind() != ElementKind.METHOD) {
        return null;
    }
    Element classElement = methodInvocationElement.getEnclosingElement();
    if (classElement == null || classElement.getKind() != ElementKind.CLASS) {
        return null;
    }
    Element classEl = enclosingMethodElement.getEnclosingElement();
    if (classEl == null || classEl.getKind() != ElementKind.CLASS) {
        return null;
    }
    boolean sameClass = classElement.equals(enclosingMethodElement.getEnclosingElement());
    if (!info.getTypes().isSubtype(classEl.asType(), classElement.asType())) {
        return null;
    }
    // classEl exts classElemenet - either classElement == classEl, or classElement cannot be final anyway
    if (classEl.getModifiers().contains(Modifier.FINAL)) {
        return null;
    }

    Set<Modifier> modifiers = methodInvocationElement.getModifiers();
    if (modifiers.contains(Modifier.PRIVATE) || 
        modifiers.contains(Modifier.FINAL) || 
        modifiers.contains(Modifier.STATIC)) {
        return null;
    }

    if (!invocationOnThis(mit)) {
        return null;
    }

    TreePath methodDeclaration = ctx.getInfo().getTrees().getPath(methodInvocationElement);

    if (methodDeclaration == null || ctx.getInfo().getTreeUtilities().isSynthetic(methodDeclaration)) return null;

    return ErrorDescriptionFactory.forName(ctx, mit,
            NbBundle.getMessage(
                OverridableMethodCallInConstructor.class,
                "MSG_org.netbeans.modules.java.hints.OverridableMethodCallInConstructor"),
                sameClass ? computeFixes((MethodTree) methodDeclaration.getLeaf(),
                    classElement, ctx) : null);
}