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

The following are Jave code examples for showing how to use getKind() of the javax.lang.model.element.TypeElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: javaide   File: PrintingProcessor.java   Source Code and License Vote up 6 votes
private void printInterfaces(TypeElement e) {
    ElementKind kind = e.getKind();

    if(kind != ANNOTATION_TYPE) {
        List<? extends TypeMirror> interfaces = e.getInterfaces();
        if (interfaces.size() > 0) {
            writer.print((kind.isClass() ? " implements" : " extends"));

            boolean first = true;
            for(TypeMirror interf: interfaces) {
                if (!first)
                    writer.print(",");
                writer.print(" ");
                writer.print(interf.toString());
                first = false;
            }
        }
    }
}
 
Example 2
Project: incubator-netbeans   File: BeanInstaller.java   Source Code and License Vote up 6 votes
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 3
Project: incubator-netbeans   File: ClassCompleter.java   Source Code and License Vote up 6 votes
private CompletionItem createItem(ElementHandle<TypeElement> handle, int priority) {
    TypeElement el = handle.resolve(ctx.getCompilationInfo());
    if (el == null) {
        // element does not exist etc
        return null;
    }
    if (el.getKind() != ElementKind.CLASS && el.getKind() != ElementKind.ENUM) {
        // do not honour interfaces
        return null;
    }
    if (!el.getModifiers().contains(Modifier.PUBLIC)) {
        return null;
    }
    CompletionItem item = null;
    
    Collection<? extends ClassItemFactory> converters = MimeLookup.getLookup(JavaFXEditorUtils.FXML_MIME_TYPE).lookupAll(ClassItemFactory.class);
    for (ClassItemFactory converter : converters) {
        item = converter.convert(el, ctx, priority);
        if (item != null) {
            break;
        }
    }
    return item;
}
 
Example 4
Project: incubator-netbeans   File: EnumValueCompleter.java   Source Code and License Vote up 6 votes
@Override
public Completer createCompleter(CompletionContext ctx) {
    FxProperty p = ctx.getEnclosingProperty();
    if (p == null || p.getType() == null) {
        return null;
    }
    TypeMirror m = p.getType().resolve(ctx.getCompilationInfo());
    if (m.getKind() == TypeKind.BOOLEAN) {
        return new EnumValueCompleter(ctx);
    }
    if (m.getKind() != TypeKind.DECLARED) {
        return null;
    }
    DeclaredType t = (DeclaredType)m;
    TypeElement tel = (TypeElement)t.asElement();
    if (tel.getQualifiedName().contentEquals("java.lang.Boolean")) {
        return new EnumValueCompleter(ctx);
    }
    if (tel.getKind() == ElementKind.ENUM) {
        return new EnumValueCompleter(ctx, tel);
    } else {
        return null;
    }
}
 
Example 5
Project: incubator-netbeans   File: PatternAnalyser.java   Source Code and License Vote up 6 votes
private void resolveTypes(Parameters p) {
    
    List<TypeElement> types = ElementFilter.typesIn(p.element.getEnclosedElements());
    
    for (TypeElement typeElement : types) {
        if ( typeElement.getKind() == ElementKind.CLASS ||
             typeElement.getKind() == ElementKind.INTERFACE ) {
            PatternAnalyser pa = new PatternAnalyser( p.ci.getFileObject(), ui );
            pa.analyzeAll(p.ci, typeElement);
            ClassPattern cp = new ClassPattern(pa, typeElement.asType(), 
                                               BeanUtils.nameAsString(typeElement));
            currentClassesPatterns.add(cp);
        }
    }

    
}
 
Example 6
Project: GitHub   File: ButterKnifeProcessor.java   Source Code and License Vote up 5 votes
private boolean isInaccessibleViaGeneratedCode(Class<? extends Annotation> annotationClass,
    String targetThing, Element element) {
  boolean hasError = false;
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify method modifiers.
  Set<Modifier> modifiers = element.getModifiers();
  if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) {
    error(element, "@%s %s must not be private or static. (%s.%s)",
        annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
        element.getSimpleName());
    hasError = true;
  }

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

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

  return hasError;
}
 
Example 7
Project: jtsgen   File: TypeScriptAnnotationProcessor.java   Source Code and License Vote up 5 votes
private Optional<TSType> handleJavaType(TypeElement element) {
    if (element == null) return Optional.empty();

    if (checkExclusion(element)) {
        LOG.info( () -> "Excluding " + element);
        return Optional.empty();
    }
    List<TSType> supertypes = convertSuperTypes(element);
    TSType result = null;

    switch (element.getKind()) {
        case CLASS:
        {
            result = TSInterfaceBuilder.of(element).withMembers(findMembers(element)).withSuperTypes(supertypes);
            break;
        }
        case INTERFACE: {
            result = TSInterfaceBuilder.of(element).withMembers(findMembers(element)).withSuperTypes(supertypes);
            break;
        }
        case ENUM: {
            result = TSEnumBuilder.of(element).withMembers(findEnumMembers(element));
            break;
        }
        default: break;
    }
   return Optional.ofNullable(result);
}
 
Example 8
Project: android-auto-mapper   File: AutoMappperProcessor.java   Source Code and License Vote up 5 votes
private void processType(TypeElement type, Map<TypeElement, String> elementTargetNames) {
    TypeElement mapFrom = getClassToMapFrom(type);
    AutoMapper autoMapper = type.getAnnotation(AutoMapper.class);
    if (autoMapper == null) {
        mErrorReporter.abortWithError(
            "annotation processor for @AutoParcel was invoked with a type annotated differently; compiler bug? O_o",
            type
        );
    }
    if (type.getKind() != ElementKind.CLASS) {
        mErrorReporter.abortWithError("@" + AutoMapper.class.getName() + " only applies to classes", type);
    }
    if (ancestorIsAutoParcel(type)) {
        mErrorReporter.abortWithError("One @AutoParcel class shall not extend another", type);
    }

    checkModifiersIfNested(type);

    // get the fully-qualified class name
    String fqClassName = generatedSubclassName(type, 0);
    // class name
    String className = TypeUtil.simpleNameOf(fqClassName);

    String source = generateClass(type, className, type.getSimpleName().toString(), mapFrom, elementTargetNames);
    source = Reformatter.fixup(source);
    writeSourceFile(fqClassName, source, type);

}
 
Example 9
Project: manifold   File: ExtensionManifold.java   Source Code and License 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 10
Project: incubator-netbeans   File: JavaClassCompletor.java   Source Code and License Vote up 5 votes
@Override
public List<TypeElement> visitType(TypeElement typeElement, Void arg) {
    if (typeElement.getKind() == ElementKind.CLASS && isAccessibleClass(typeElement)) {
        DEFAULT_VALUE.add(typeElement);
    }
    return super.visitType(typeElement, arg);
}
 
Example 11
Project: incubator-netbeans   File: ObjectProviders.java   Source Code and License 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 12
Project: incubator-netbeans   File: JavaI18nSupport.java   Source Code and License Vote up 5 votes
/**
 * Finds a main top-level class or a nested class element
 * for {@code sourceDataObject} which should be initialized.
 */
private TypeElement getClass(WorkingCopy workingCopy)
                                                    throws IOException {
    workingCopy.toPhase(Phase.ELEMENTS_RESOLVED);

    final String preferredName = sourceDataObject.getName();
    TypeElement firstPublicNestedClass = null;
    
    List<? extends TypeElement> topClasses = workingCopy.getTopLevelElements();
    for (TypeElement topElement : topClasses) {
        ElementKind elementKind = topElement.getKind();
        if (!elementKind.isClass()) {
            continue;
        }

        if (topElement.getSimpleName().contentEquals(preferredName)) {
            return topElement;
        }

        if ((firstPublicNestedClass == null)
                && topElement.getModifiers().contains(Modifier.PUBLIC)) {
            firstPublicNestedClass = topElement;
        }
    }

    return firstPublicNestedClass;
}
 
Example 13
Project: incubator-netbeans   File: AbstractTestGenerator.java   Source Code and License Vote up 5 votes
/**
 * Checks whether the given type object represents type
 * {@literal java.lang.Object}.
 * 
 * @param  type  type to be checked
 * @return  {@literal true} if the passed type object represents type
 *          {@literal java.lang.Object}, {@literal false} otherwise
 */
private static boolean isRootObjectType(DeclaredType type) {
    if (type.getKind() != TypeKind.DECLARED) {
        return false;
    }

    TypeElement elem = (TypeElement) type.asElement();
    return (elem.getKind() == ElementKind.CLASS)
           && (elem.getSuperclass().getKind() == TypeKind.NONE);
}
 
Example 14
Project: CustomAnnotation   File: ProxyToolProcessor.java   Source Code and License Vote up 5 votes
/**
 * 注解是否有效
 * @author leibing
 * @createTime 2017/3/2
 * @lastModify 2017/3/2
 * @param annotationClass
 * @param targetThing
 * @param element 元素
 * @return
 */
private boolean isValid(Class<? extends Annotation> annotationClass, String targetThing, Element element) {
    boolean isVaild = true;
    // 获取变量的所在的父元素,肯能是类、接口、枚举
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    // 父元素的全限定名
    String qualifiedName = enclosingElement.getQualifiedName().toString();
    // 所在的类不能是private或static修饰
    Set<Modifier> modifiers = element.getModifiers();
    if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) {
        error(element, "@%s %s must not be private or static. (%s.%s)",
                annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
                element.getSimpleName());
        isVaild = false;
    }
    // 父元素必须是类,而不能是接口或枚举
    if (enclosingElement.getKind() != ElementKind.CLASS) {
        error(enclosingElement, "@%s %s may only be contained in classes. (%s.%s)",
                annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
                element.getSimpleName());
        isVaild = false;
    }
    // 不能在Android框架层注解
    if (qualifiedName.startsWith("android.")) {
        error(element, "@%s-annotated class incorrectly in Android framework package. (%s)",
                annotationClass.getSimpleName(), qualifiedName);
        return false;
    }
    // 不能在java框架层注解
    if (qualifiedName.startsWith("java.")) {
        error(element, "@%s-annotated class incorrectly in Java framework package. (%s)",
                annotationClass.getSimpleName(), qualifiedName);
        return false;
    }

    return isVaild;
}
 
Example 15
Project: react4j   File: ReactProcessor.java   Source Code and License 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 16
Project: GitHub   File: Constitution.java   Source Code and License Vote up 4 votes
InnerBuilderDefinition() {
  @Nullable TypeElement builderElement = findBuilderElement();
  // The following series of checks designed
  // to not validate inner builder if it's disabled,
  // but at the same time we need such validation
  // if we are using "extending" builder which is still allowed
  // on demand even if builder feature is disabled
  boolean extending = false;

  if (builderElement != null) {
    extending = isExtending(builderElement);
  }

  if (builderElement != null && !protoclass().features().builder() && !extending) {
    builderElement = null;
  }

  if (builderElement != null && !isValidInnerBuilder(builderElement)) {
    builderElement = null;
  }

  if (builderElement != null) {
    this.isAccessibleFields = AccessibleFieldsMirror.find(builderElement).isPresent();
    this.isPresent = true;
    this.isInterface = builderElement.getKind() == ElementKind.INTERFACE;
    this.isExtending = extending;
    this.isSuper = !extending;
    this.simpleName = builderElement.getSimpleName().toString();
    this.visibility = Visibility.of(builderElement);
    this.generics = new Generics(protoclass(), builderElement);
    if (isExtending) {
      lateValidateExtending(builderElement);
    }
    if (isSuper) {
      lateValidateSuper(builderElement);
    }
  } else {
    this.isAccessibleFields = false;
    this.isPresent = false;
    this.isInterface = false;
    this.isExtending = false;
    this.isSuper = false;
    this.visibility = Visibility.PRIVATE;
    this.simpleName = null;
    this.generics = Generics.empty();
  }
}
 
Example 17
Project: jtsgen   File: TypeScriptAnnotationProcessor.java   Source Code and License 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 18
Project: GitHub   File: Encodings.java   Source Code and License Vote up 4 votes
Encoding(TypeElement type) {
  this.typeEncoding = type;
  if (type.getKind() != ElementKind.CLASS || type.getNestingKind() != NestingKind.TOP_LEVEL) {
    reporter.withElement(type).error("Encoding type '%s' should be top-level class", type.getSimpleName());
  }

  this.$$package = processing().getElementUtils().getPackageOf(type).getQualifiedName().toString();
  this.name = type.getSimpleName().toString();

  CharSequence source = SourceExtraction.extract(processing(), type);
  if (source.length() == 0) {
    reporter.withElement(type)
        .error("No source code can be extracted for @Encoding class. Unsupported compilation mode");
  }

  this.imports = SourceExtraction.importsFrom(source);
  this.sourceMapper = new SourceMapper(source);
  this.typesReader = new TypeExtractor(types, type);

  this.encodingSelfType = typesReader.get(type.asType());

  addTypeParameters(type);

  for (Element e : type.getEnclosedElements()) {
    processMember(e);
  }

  if (postValidate()) {
    provideSyntheticElements();
  }

  this.allElements = Iterables.concat(
      Arrays.asList(
          Iterables.filter(
              Arrays.asList(
                  impl,
                  from,
                  toString,
                  hashCode,
                  equals,
                  build), Predicates.notNull()),
          fields,
          expose,
          copy,
          helpers,
          builderFields,
          builderHelpers,
          builderInits));

  this.linkage = new Linkage();
  this.nonlinkedImports = nonlinkedImports();
}
 
Example 19
Project: incubator-netbeans   File: TopClassFinder.java   Source Code and License Vote up 4 votes
public boolean passes(TypeElement topClass,
                      CompilationInfo compInfo) {
    ElementKind elemKind = topClass.getKind();
    return (elemKind != ElementKind.ANNOTATION_TYPE)
           && (elemKind.isClass()|| elemKind.isInterface());
}
 
Example 20
Project: incubator-netbeans   File: ImportClassPanel.java   Source Code and License Vote up 4 votes
public TypeDescription(TypeElement typeElement, boolean isDenied ) {
   this.isDenied = isDenied;
   this.kind = typeElement.getKind();
   this.qualifiedName = typeElement.getQualifiedName().toString();
}