Java Code Examples for javax.lang.model.element.ElementKind.INTERFACE

The following are Jave code examples for showing how to use INTERFACE of the javax.lang.model.element.ElementKind class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: autoproxy   File: CommonClassGenerator.java   View Source Code Vote up 6 votes
@NonNull
protected TypeSpec.Builder createClass(@NonNull final FieldSpec... members) {
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Proxy_" + type.flatClassName)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);

    // TODO: mimic annotations of the super type

    if (ElementKind.INTERFACE == type.element.getKind()) {
        builder.addSuperinterface(superType);
    } else if (ElementKind.CLASS == type.element.getKind()) {
        builder.superclass(superType);
    } else {
        final String message = "Unsupported data type: " + type.element.getKind() + ", " + type.elementType;
        errors.write(message + "\n");

        throw new UnsupportedOperationException(message);
    }

    for (final FieldSpec member : members) {
        builder.addField(member);
    }

    return builder;
}
 
Example 2
Project: incubator-netbeans   File: DocumentUtil.java   View Source Code Vote up 6 votes
@NonNull
static ElementKind decodeKind (char kind) {
    switch (kind) {
        case EK_CLASS:
        case EK_LOCAL_CLASS:
            return ElementKind.CLASS;
        case EK_INTERFACE:
        case EK_LOCAL_INTERFACE:
            return ElementKind.INTERFACE;
        case EK_ENUM:
        case EK_LOCAL_ENUM:
            return ElementKind.ENUM;
        case EK_ANNOTATION:
        case EK_LOCAL_ANNOTATION:
            return ElementKind.ANNOTATION_TYPE;
        case EK_MODULE:
            return ElementKind.MODULE;
        default:
            throw new IllegalArgumentException ();
    }
}
 
Example 3
Project: dataenum   File: SpecParser.java   View Source Code Vote up 6 votes
public static Spec parse(Element element, ProcessingEnvironment processingEnv) {
  Messager messager = processingEnv.getMessager();

  if (element.getKind() != ElementKind.INTERFACE) {
    messager.printMessage(
        Diagnostic.Kind.ERROR, "@DataEnum can only be used on interfaces.", element);
    return null;
  }

  TypeElement dataEnum = (TypeElement) element;

  List<TypeVariableName> typeVariableNames = new ArrayList<>();
  for (TypeParameterElement typeParameterElement : dataEnum.getTypeParameters()) {
    typeVariableNames.add(TypeVariableName.get(typeParameterElement));
  }

  List<Value> values = ValuesParser.parse(dataEnum, processingEnv);
  if (values == null) {
    return null;
  }

  ClassName enumInterface = ClassName.get(dataEnum);
  return new Spec(enumInterface, typeVariableNames, values);
}
 
Example 4
Project: openjdk-jdk10   File: Symbol.java   View Source Code Vote up 5 votes
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    long flags = flags();
    if ((flags & ANNOTATION) != 0)
        return ElementKind.ANNOTATION_TYPE;
    else if ((flags & INTERFACE) != 0)
        return ElementKind.INTERFACE;
    else if ((flags & ENUM) != 0)
        return ElementKind.ENUM;
    else
        return ElementKind.CLASS;
}
 
Example 5
Project: incubator-netbeans   File: DocumentUtil.java   View Source Code Vote up 5 votes
@NonNull
public static Convertor<Document,ElementHandle<TypeElement>> typeElementConvertor() {
    return new ElementHandleConvertor<> (
            ElementKind.CLASS,
            ElementKind.ENUM,
            ElementKind.INTERFACE,
            ElementKind.ANNOTATION_TYPE);
}
 
Example 6
Project: remoter   File: RemoterProcessor.java   View Source Code Vote up 5 votes
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    for (Element element : env.getElementsAnnotatedWith(Remoter.class)) {
        if (element.getKind() == ElementKind.INTERFACE) {
            bindingManager.generateProxy(element);
            bindingManager.generateStub(element);
        } else {
            messager.printMessage(Diagnostic.Kind.WARNING, "@Remoter is expected only for interface. Ignoring " + element.getSimpleName());
        }
    }
    return false;
}
 
Example 7
Project: incubator-netbeans   File: WorkingCopy.java   View Source Code Vote up 5 votes
FileObject doCreateFromTemplate(CompilationUnitTree cut) throws IOException {
    ElementKind kind;
    if ("package-info.java".equals(cut.getSourceFile().getName())) {
        kind = ElementKind.PACKAGE;
    } else if (cut.getTypeDecls().isEmpty()) {
        kind = null;
    } else {
        switch (cut.getTypeDecls().get(0).getKind()) {
            case CLASS:
                kind = ElementKind.CLASS;
                break;
            case INTERFACE:
                kind = ElementKind.INTERFACE;
                break;
            case ANNOTATION_TYPE:
                kind = ElementKind.ANNOTATION_TYPE;
                break;
            case ENUM:
                kind = ElementKind.ENUM;
                break;
            default:
                Logger.getLogger(WorkingCopy.class.getName()).log(Level.SEVERE, "Cannot resolve template for {0}", cut.getTypeDecls().get(0).getKind());
                kind = null;
        }
    }
    FileObject template = FileUtil.getConfigFile(template(kind));
    return doCreateFromTemplate(template, cut.getSourceFile());
}
 
Example 8
Project: incubator-netbeans   File: ObjectProviders.java   View Source Code Vote up 5 votes
@Override
public List<T> createObjects(TypeElement type) {
    final List<T> result = new ArrayList<T>();
    if (type.getKind() == ElementKind.CLASS || type.getKind() == ElementKind.INTERFACE) {
        if (helper.hasAnyAnnotation(type.getAnnotationMirrors(), getAnnotationTypeNames())) {
            result.add(createObject(helper, type));
        }
    }
    return result;
}
 
Example 9
Project: incubator-netbeans   File: FindOverridingVisitor.java   View Source Code Vote up 5 votes
@Override
public Tree visitLambdaExpression(LambdaExpressionTree node, Element elementToFind) {
    Element type = elementToFind.getEnclosingElement();
    if (type.getKind() == ElementKind.INTERFACE &&
            workingCopy.getElements().isFunctionalInterface((TypeElement) type) &&
            !workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
        
        TypeMirror typeMirror = workingCopy.getTrees().getTypeMirror(getCurrentPath());
        
        if (typeMirror != null && workingCopy.getTypes().isSameType(typeMirror, type.asType())) {
            addUsage(getCurrentPath());
        }
    }
    return super.visitLambdaExpression(node, elementToFind);
}
 
Example 10
Project: manifold   File: ExtensionManifold.java   View Source Code Vote up 5 votes
@Override
public void process( TypeElement typeElement, TypeProcessor typeProcessor, IssueReporter<JavaFileObject> issueReporter )
{
  if( typeElement.getKind() == ElementKind.CLASS || typeElement.getKind() == ElementKind.INTERFACE )
  {
    TreeTranslator visitor = new ExtensionTransformer( this, typeProcessor );
    typeProcessor.getTree().accept( visitor );
  }
}
 
Example 11
Project: incubator-netbeans   File: CreateElement.java   View Source Code Vote up 5 votes
private static ElementKind getClassType(Set<ElementKind> types) {
    if (types.contains(ElementKind.CLASS))
        return ElementKind.CLASS;
    if (types.contains(ElementKind.ANNOTATION_TYPE))
        return ElementKind.ANNOTATION_TYPE;
    if (types.contains(ElementKind.INTERFACE))
        return ElementKind.INTERFACE;
    if (types.contains(ElementKind.ENUM))
        return ElementKind.ENUM;

    return null;
}
 
Example 12
Project: incubator-netbeans   File: InstanceRefFinder.java   View Source Code Vote up 5 votes
protected TypeElement findOwnerType(Element el) {
    Element t;
    if (el instanceof TypeElement) {
        t = ((TypeElement)el);
    } else {
        t = ci.getElementUtilities().enclosingTypeElement(el);
        if (t == null) {
            return null;
        }
    }
    ElementKind k = t.getKind();
    TypeMirror declType = ci.getTypes().erasure(t.asType());
    
    for (TypeElement enclType = enclosingType; enclType != null; enclType = ci.getElementUtilities().enclosingTypeElement(enclType)) {
        if (ci.getTypes().isSubtype(ci.getTypes().erasure(enclType.asType()), declType)) {
            if (k.isClass()) {
                return enclType;
            } else if (k == ElementKind.INTERFACE) {
                if (t.getModifiers().contains(Modifier.DEFAULT)) {
                    return enclType;
                }
            }
            break;
        }
    }
    // PENDING - this is strange, report an error ??
    return null;
}
 
Example 13
Project: incubator-netbeans   File: CreateSubclass.java   View Source Code Vote up 4 votes
@TriggerTreeKind({Tree.Kind.CLASS, Tree.Kind.INTERFACE})
public static ErrorDescription check(HintContext context) {
    TreePath tp = context.getPath();
    ClassTree cls = (ClassTree) tp.getLeaf();
    CompilationInfo info = context.getInfo();
    SourcePositions sourcePositions = info.getTrees().getSourcePositions();
    long startPos = sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
    if (startPos > Integer.MAX_VALUE) {
        return null;
    }
    int[] bodySpan = info.getTreeUtilities().findBodySpan(cls);
    if (bodySpan == null || bodySpan[0] <= startPos) {
        return null;
    }
    int caret = context.getCaretLocation();
    if (startPos < 0 || caret < 0 || caret < startPos || caret >= bodySpan[0]) {
        return null;
    }

    // #222487
    // If there is a compile-time error on the class, then don't offer to
    // create a subclass.
    List<Diagnostic> errors = info.getDiagnostics();
    if (!errors.isEmpty()) {
        for (Diagnostic d : errors) {
            if (d.getKind() != Diagnostic.Kind.ERROR) {
                continue;
            }
            // Check that the error's start position is within the class header
            // Note: d.getEndPosition() is not used because, for example,
            // a "compiler.err.does.not.override.abstract" error ends at
            // the end of the class tree.
            if (startPos <= d.getStartPosition() && d.getStartPosition() <= bodySpan[0]) {
                return null;
            }
        }
    }

    TypeElement typeElement = (TypeElement) info.getTrees().getElement(tp);
    
    if (typeElement == null || typeElement.getModifiers().contains(Modifier.FINAL)) return null;

    Element outer = typeElement.getEnclosingElement();
    // do not offer the hint for non-static inner classes. Permit for classes nested into itnerface - no enclosing instance
    if (outer != null && outer.getKind() != ElementKind.PACKAGE && outer.getKind() != ElementKind.INTERFACE) {
        if (outer.getKind() != ElementKind.CLASS && outer.getKind() != ElementKind.ENUM) {
            return null;
        }
        if (!typeElement.getModifiers().contains(Modifier.STATIC)) {
            return null;
        }
    }

    
    ClassPath cp = info.getClasspathInfo().getClassPath(PathKind.SOURCE);
    FileObject root = cp.findOwnerRoot(info.getFileObject());
    if (root == null) { //File not part of any project
        return null;
    }

    PackageElement packageElement = (PackageElement) info.getElementUtilities().outermostTypeElement(typeElement).getEnclosingElement();
    CreateSubclassFix fix = new CreateSubclassFix(info, root, packageElement.getQualifiedName().toString(), typeElement.getSimpleName().toString() + "Impl", typeElement); //NOI18N
    return ErrorDescriptionFactory.forTree(context, context.getPath(), NbBundle.getMessage(CreateSubclass.class, typeElement.getKind() == ElementKind.CLASS
            ? typeElement.getModifiers().contains(Modifier.ABSTRACT) ? "ERR_ImplementAbstractClass" : "ERR_CreateSubclass" : "ERR_ImplementInterface"), fix); //NOI18N
}
 
Example 14
Project: GitHub   File: ValueType.java   View Source Code Vote up 4 votes
public boolean isImplementing() {
  return element.getKind() == ElementKind.INTERFACE
      || element.getKind() == ElementKind.ANNOTATION_TYPE;
}
 
Example 15
Project: GitHub   File: ValueAttribute.java   View Source Code Vote up 4 votes
public boolean isInterfaceDefaultMethod() {
  return element.getEnclosingElement().getKind() == ElementKind.INTERFACE
      && !element.getModifiers().contains(Modifier.ABSTRACT);
}
 
Example 16
Project: incubator-netbeans   File: ExpectedTypeResolver.java   View Source Code Vote up 4 votes
/**
 * For member select, find the most generic type which declares that member.
 * When traversing up the inheritance tree, the return type must be checked, as it may
 * become too general to fit the parent expression's requirements.
 */
@Override
public List<? extends TypeMirror> visitMemberSelect(MemberSelectTree tree, Object v) {
    if (casted != null) {
        // if the casted type is a primitive, the cast is NOT redundant as member select is applied to
        // the originally primitive value.
        TypeMirror castedType = info.getTrees().getTypeMirror(casted);
        if (castedType != null && castedType.getKind().isPrimitive()) {
            notRedundant = true;
        }
    }
    // must compute expected type of the method:
    TreePath[] p = new TreePath[1];
    ExpressionTree[] e = new ExpressionTree[1];
    Tree[] l = new Tree[1];
    List<TypeMirror> tt = new ArrayList<TypeMirror>();
    Element el = info.getTrees().getElement(getCurrentPath());
    
    if (el == null) {
        return null;
    }
    
    if (el.getKind() == ElementKind.METHOD) {
        // special hack: if the casted value is a lambda, we NEED to assign it a type prior to method invocation:
        TreePath exp = getExpressionWithoutCasts();
        if (exp != null && exp.getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) {
            return null;
        }
        TreePath methodInvocation = getCurrentPath().getParentPath();
        TreePath invocationParent = methodInvocation.getParentPath();
        ExpectedTypeResolver subResolver = new ExpectedTypeResolver(methodInvocation, info);
        subResolver.theExpression = methodInvocation;
        subResolver.typeCastDepth++;
        List<? extends TypeMirror> parentTypes = subResolver.scan(invocationParent, v);
        TypeMirror castable = null;
        if (parentTypes == null) {
            castable = subResolver.getCastableTo();
        }
        if (parentTypes != null || castable != null) {
            TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree.getExpression()));
            if (!(exprType instanceof DeclaredType)) {
                return null;
            }
            ExecutableElement elem = (ExecutableElement)el;
            TreePath method = getCurrentPath();
            while (method != null && method.getLeaf().getKind() != Tree.Kind.METHOD) {
                method = method.getParentPath();
            }
            if (method == null) {
                method = getCurrentPath();
            }
            List<TypeMirror> cans = findBaseTypes(info, elem, (DeclaredType)exprType,
                    parentTypes, 
                    castable, 
                    info.getTrees().getScope(method));
            if (!cans.isEmpty()) {
                return cans;
            }
        } else {
            TypeMirror exprm = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree.getExpression()));
            return Collections.singletonList(exprm);
        }
    } else if (el.getKind() == ElementKind.FIELD) {
        // access to a field
        Element parent = el.getEnclosingElement();
        if (parent.getKind() == ElementKind.CLASS || parent.getKind() == ElementKind.INTERFACE || parent.getKind() == ElementKind.ENUM) {
            return Collections.singletonList(parent.asType());
        }
    }
    return null;
}
 
Example 17
Project: react4j   File: ReactProcessor.java   View Source Code Vote up 4 votes
private void determineEventHandlers( @Nonnull final ComponentDescriptor descriptor )
{
  final List<EventHandlerDescriptor> eventHandlers =
    ProcessorUtil.getMethods( descriptor.getElement(), processingEnv.getTypeUtils() ).stream()
      .filter( m -> null != ProcessorUtil.findAnnotationByType( m, Constants.EVENT_HANDLER_ANNOTATION_CLASSNAME ) )
      .map( m -> createEventHandlerDescriptor( descriptor, m ) )
      .collect( Collectors.toList() );
  for ( final EventHandlerDescriptor eventHandler : eventHandlers )
  {
    final ExecutableElement method = eventHandler.getMethod();
    final TypeElement handlerType = getEventHandlerType( method );
    if ( ElementKind.INTERFACE != handlerType.getKind() )
    {
      throw new ReactProcessorException( "The @EventHandler specified an invalid type that is not an interface.",
                                         eventHandler.getMethod() );
    }
    if ( null == ProcessorUtil.findAnnotationByType( handlerType, Constants.JS_FUNCTION_CLASSNAME ) )
    {
      throw new ReactProcessorException( "The @EventHandler specified an invalid type that is not annotated " +
                                         "with the annotation jsinterop.annotations.JsFunction.",
                                         eventHandler.getMethod() );
    }
    final EventHandlerDescriptor matched = eventHandlers.stream()
      .filter( h -> h != eventHandler && h.getName().equals( eventHandler.getName() ) )
      .findAny().orElse( null );
    if ( null != matched )
    {
      throw new ReactProcessorException( "The @EventHandler has the same name as the event handler defined by " +
                                         matched.getMethod() + ".", eventHandler.getMethod() );
    }
    final EventHandlerDescriptor matched2 = eventHandlers.stream()
      .filter( h -> h != eventHandler &&
                    h.getMethod().getSimpleName().equals( eventHandler.getMethod().getSimpleName() ) )
      .findAny().orElse( null );
    if ( null != matched2 )
    {
      throw new ReactProcessorException( "The @EventHandler has the same method name as the event handler defined " +
                                         "by " + matched2.getMethod() + ".", eventHandler.getMethod() );
    }
    final ExecutableType methodType = eventHandler.getMethodType();
    final List<? extends TypeMirror> parameters = methodType.getParameterTypes();
    if ( !parameters.isEmpty() )
    {
      // Our annotated handler method has parameters so they should exactly align
      // in count and type with the parameters in the event handler method
      final ExecutableElement target = eventHandler.getEventHandlerMethod();
      final List<? extends VariableElement> targetParameters = target.getParameters();
      if ( targetParameters.size() != parameters.size() )
      {
        throw new ReactProcessorException( "The @EventHandler target has " + parameters.size() + " parameters " +
                                           "but the type parameter specified a handler with method type " +
                                           eventHandler.getEventHandlerType().getQualifiedName() + " that has " +
                                           "handler method with " + targetParameters.size() + " parameters. The " +
                                           "@EventHandler target should have zero parameters or match the number " +
                                           "of parameter in the target method " + target.getSimpleName() + ".",
                                           eventHandler.getMethod() );
      }
      for ( int i = 0; i < parameters.size(); i++ )
      {
        final TypeMirror parameterType = parameters.get( i );
        final VariableElement element = targetParameters.get( i );
        final TypeMirror targetParameterType = element.asType();
        final TypeMirror targetErased = processingEnv.getTypeUtils().erasure( targetParameterType );
        final TypeMirror parameterErased = processingEnv.getTypeUtils().erasure( parameterType );
        if ( !processingEnv.getTypeUtils().isAssignable( targetErased, parameterErased ) )
        {
          throw new ReactProcessorException( "The @EventHandler target parameter named " +
                                             eventHandler.getMethod().getParameters().get( i ).getSimpleName() +
                                             " of type " + parameterType + " is not assignable from target type " +
                                             targetParameterType + " of parameter " + element.getSimpleName() +
                                             " in method " + eventHandler.getEventHandlerType().getQualifiedName() +
                                             "." + target.getSimpleName() + ".",
                                             eventHandler.getMethod() );
        }
      }
    }
  }

  descriptor.setEventHandlers( eventHandlers );
}
 
Example 18
Project: openjdk-jdk10   File: GraphNodeVerifier.java   View Source Code Vote up 4 votes
private void scanFields(TypeElement node) {
    TypeElement currentClazz = node;
    do {
        for (VariableElement field : ElementFilter.fieldsIn(currentClazz.getEnclosedElements())) {
            Set<Modifier> modifiers = field.getModifiers();
            if (modifiers.contains(STATIC) || modifiers.contains(TRANSIENT)) {
                continue;
            }

            List<? extends AnnotationMirror> annotations = field.getAnnotationMirrors();

            boolean isNonOptionalInput = findAnnotationMirror(annotations, Input) != null;
            boolean isOptionalInput = findAnnotationMirror(annotations, OptionalInput) != null;
            boolean isSuccessor = findAnnotationMirror(annotations, Successor) != null;

            if (isNonOptionalInput || isOptionalInput) {
                if (findAnnotationMirror(annotations, Successor) != null) {
                    throw new ElementException(field, "Field cannot be both input and successor");
                } else if (isNonOptionalInput && isOptionalInput) {
                    throw new ElementException(field, "Inputs must be either optional or non-optional");
                } else if (isAssignableWithErasure(field, NodeInputList)) {
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Input list field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Input list field must not be public");
                    }
                } else {
                    if (!isAssignableWithErasure(field, Node) && field.getKind() == ElementKind.INTERFACE) {
                        throw new ElementException(field, "Input field type must be an interface or assignable to Node");
                    }
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Input field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Input field must not be public");
                    }
                }
            } else if (isSuccessor) {
                if (isAssignableWithErasure(field, NodeSuccessorList)) {
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Successor list field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Successor list field must not be public");
                    }
                } else {
                    if (!isAssignableWithErasure(field, Node)) {
                        throw new ElementException(field, "Successor field must be a Node type");
                    }
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Successor field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Successor field must not be public");
                    }
                }

            } else {
                if (isAssignableWithErasure(field, Node) && !field.getSimpleName().contentEquals("Null")) {
                    throw new ElementException(field, "Node field must be annotated with @" + Input.getSimpleName() + ", @" + OptionalInput.getSimpleName() + " or @" + Successor.getSimpleName());
                }
                if (isAssignableWithErasure(field, NodeInputList)) {
                    throw new ElementException(field, "NodeInputList field must be annotated with @" + Input.getSimpleName() + " or @" + OptionalInput.getSimpleName());
                }
                if (isAssignableWithErasure(field, NodeSuccessorList)) {
                    throw new ElementException(field, "NodeSuccessorList field must be annotated with @" + Successor.getSimpleName());
                }
                if (modifiers.contains(PUBLIC) && !modifiers.contains(FINAL)) {
                    throw new ElementException(field, "Data field must be final if public");
                }
            }
        }
        currentClazz = getSuperType(currentClazz);
    } while (!isObject(getSuperType(currentClazz).asType()));
}
 
Example 19
Project: jtsgen   File: TypeScriptAnnotationProcessor.java   View Source Code Vote up 4 votes
private boolean isMarkerInterface(TypeElement typeElement) {
    boolean isMarker = typeElement.getKind() == ElementKind.INTERFACE
            && typeElement.getEnclosedElements().size() == 0;
    if (isMarker) LOG.fine(() -> "TSAP " + typeElement + " is marker interface");
    return isMarker;
}
 
Example 20
Project: vxrifa   File: VxRifaAnnotationProcessor.java   View Source Code Vote up 3 votes
private boolean isNotInterfaceElement(Element element) {
    
    if (element.getKind() != ElementKind.INTERFACE) {
        messager.printMessage(Diagnostic.Kind.ERROR, "This annotation can be applied only to interfaces!", element, element.getAnnotationMirrors().get(0));
        return true;
    }
    
    return false;

}