javax.lang.model.element.Element#getAnnotation ( )源码实例Demo

下面列出了javax.lang.model.element.Element#getAnnotation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Processes the conditional annotations for a component into a dictionary
 * mapping blocks to those annotations.
 *
 * @param componentInfo Component info in which to store the conditional information.
 * @param element The currently processed Java language element. This should be a method
 *                annotated with either @UsesPermission or @UsesBroadcastReceivers.
 * @param blockName The name of the block as it appears in the sources.
 */
private void processConditionalAnnotations(ComponentInfo componentInfo, Element element,
                                           String blockName) {
  // Conditional UsesPermissions
  UsesPermissions usesPermissions = element.getAnnotation(UsesPermissions.class);
  if (usesPermissions != null) {
    componentInfo.conditionalPermissions.put(blockName, usesPermissions.value());
  }

  UsesBroadcastReceivers broadcastReceiver = element.getAnnotation(UsesBroadcastReceivers.class);
  if (broadcastReceiver != null) {
    try {
      Set<String> receivers = new HashSet<>();
      for (ReceiverElement re : broadcastReceiver.receivers()) {
        updateWithNonEmptyValue(receivers, receiverElementToString(re));
      }
      componentInfo.conditionalBroadcastReceivers.put(blockName, receivers.toArray(new String[0]));
    } catch (Exception e) {
      messager.printMessage(Kind.ERROR, "Unable to process broadcast receiver", element);
    }
  }
}
 
源代码2 项目: EasyMVP   文件: EasyMVPProcessor.java
private void parseConductorController(Element element,
                                      Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
    if (!SuperficialValidation.validateElement(element)) {
        error("Superficial validation error for %s", element.getSimpleName());
        return;
    }
    if (!Validator.isNotAbstractClass(element)) {
        error("%s is abstract", element.getSimpleName());
        return;
    }
    if (!Validator.isSubType(element, CONDUCTOR_CONTROLLER_CLASS_NAME, processingEnv)) {
        error("%s must extend View", element.getSimpleName());
        return;
    }
    //getEnclosing for class type will returns its package/
    TypeElement enclosingElement = (TypeElement) element;
    DelegateClassGenerator delegateClassGenerator =
            getDelegate(enclosingElement, delegateClassMap);
    delegateClassGenerator.setViewType(ViewType.CONDUCTOR_CONTROLLER);
    ConductorController annotation = element.getAnnotation(ConductorController.class);
    try {
        annotation.presenter();
    } catch (MirroredTypeException mte) {
        parsePresenter(delegateClassGenerator, mte);
    }
}
 
/**
 * 主要的处理注解的类,会拿到所有的注解相关的类
 *
 * @param annotations
 * @param roundEnv
 * @return 处理成功返回true
 */
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    List<HTAnnotatedClass> annotatedClasses = new ArrayList<>();
    //获取所有通过HTRouter注解的项,遍历
    for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(HTRouter.class)) {
        TypeElement annotatedClass = (TypeElement) annotatedElement;
        //检测是否是支持的注解类型,如果不是里面会报错
        if (!isValidClass(annotatedClass)) {
            return true;
        }
        //获取到信息,把注解类的信息加入到列表中
        HTRouter htRouter = annotatedElement.getAnnotation(HTRouter.class);
        annotatedClasses.add(new HTAnnotatedClass(annotatedClass, htRouter.url(), htRouter.entryAnim(), htRouter.exitAnim()));
    }

    //生成各种类
    for (Integer type : CODE_TYPE_MAP.keySet()){
        try {
            generateCode(annotatedClasses, type);
        } catch (IOException e) {
            messager.printMessage(ERROR, CODE_TYPE_MAP.get(type));
        }
    }
    return true;
}
 
源代码4 项目: openjdk-jdk8u   文件: LVTHarness.java
@Override
public boolean process(Set<? extends TypeElement> annotations,
    RoundEnvironment roundEnv) {
    if (roundEnv.processingOver())
        return true;

    TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");

    if (!annotations.contains(aliveRangeAnno)) {
        error("no @AliveRanges annotation found in test class");
    }

    for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
        Annotation annotation = elem.getAnnotation(AliveRanges.class);
        aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
    }
    return true;
}
 
源代码5 项目: TencentKona-8   文件: LVTHarness.java
@Override
public boolean process(Set<? extends TypeElement> annotations,
    RoundEnvironment roundEnv) {
    if (roundEnv.processingOver())
        return true;

    TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");

    if (!annotations.contains(aliveRangeAnno)) {
        error("no @AliveRanges annotation found in test class");
    }

    for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
        Annotation annotation = elem.getAnnotation(AliveRanges.class);
        aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
    }
    return true;
}
 
源代码6 项目: hottub   文件: InlineAnnotationReaderImpl.java
/**
 * Gets all the annotations on the given declaration.
 */
private Annotation[] getAllAnnotations(Element decl, Locatable srcPos) {
    List<Annotation> r = new ArrayList<Annotation>();

    for( AnnotationMirror m : decl.getAnnotationMirrors() ) {
        try {
            String fullName = ((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString();
            Class<? extends Annotation> type =
                SecureLoader.getClassClassLoader(getClass()).loadClass(fullName).asSubclass(Annotation.class);
            Annotation annotation = decl.getAnnotation(type);
            if(annotation!=null)
                r.add( LocatableAnnotation.create(annotation,srcPos) );
        } catch (ClassNotFoundException e) {
            // just continue
        }
    }

    return r.toArray(new Annotation[r.size()]);
}
 
源代码7 项目: Modularity   文件: APTProcessor.java
@Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        try {
            JavaFileObject f = processingEnv.getFiler().createSourceFile(CLASSNAME);
            Writer w = f.openWriter();
            PrintWriter pw = new PrintWriter(w);
            for (TypeElement te : annotations) {
                pw.println("package " + PACKAGENAME + ";");
                pw.println("\npublic class " + CLASSNAME + " { ");
                for (Element element : roundEnv.getElementsAnnotatedWith(te)) {
                    RList annotation = element.getAnnotation(RList.class);
                    String name = annotation.name();
                    String value = element.toString();
//                    String packageName = element.getEnclosingElement().toString();

                    pw.println("    public static final String " + name + " = \"" + value + "\";");
                }
                pw.println("}");
                pw.flush();
            }
        } catch (IOException x) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    x.toString());
        }
        return true;
    }
 
private void processMappedAnnotationElements() {
    for (Element mappedElement : roundEnvironment.getElementsAnnotatedWith(Mapped.class)) {
        if (mappedElement.getKind() == ElementKind.FIELD) {
            Mapped mappedAnnotation = mappedElement.getAnnotation(Mapped.class);

            String fieldName = mappedElement.getSimpleName().toString();
            String fieldType = mappedElement.asType().toString();
            boolean isPublicField = mappedElement.getModifiers().contains(Modifier.PUBLIC);
            String toFieldName = mappedAnnotation.toField();

            MapperFieldInfo mappingFieldInfo = new MapperFieldInfo(fieldName, fieldType, toFieldName, isPublicField);

            ClassInfo classInfo = extractClassInformationFromField(mappedElement);
            getMapper(classInfo)
                        .getFields()
                            .add(mappingFieldInfo);
        }
    }
}
 
private boolean parseSubmodules(Set<? extends Element> submoduleDatabaseElements) {
  if (submoduleDatabaseElements.size() > 1) {
    environment.error(ERR_SINGLE_SUBMODULE_DB_ALLOWED);
    return false;
  }
  for (Element element : submoduleDatabaseElements) {
    if (environment.getSubmoduleName() == null) {
      final SubmoduleDatabase submoduleDatabase = element.getAnnotation(SubmoduleDatabase.class);
      final String moduleName = submoduleDatabase.value();
      if (Strings.isNullOrEmpty(moduleName)) {
        environment.error(element, "Submodule name cannot be empty or null");
      }
      environment.setSubmoduleName(firstCharToUpperCase(moduleName));
    } else {
      environment.error(element, ERR_SINGLE_SUBMODULE_DB_ALLOWED);
      return false;
    }
  }
  return true;
}
 
源代码10 项目: alchemy   文件: RelationRule.java
private void processOneToOne(Element field, Element relation) {
    if (relation.getAnnotation(Entry.class) == null) {
        throw new ElementException("Related type must be annotated with @Entry", relation);
    }
    final Element enclosingElement = field.getEnclosingElement();
    final TableSpec lTable = mCompileGraph.findTableSpec(enclosingElement);
    final TableSpec rTable = mCompileGraph.findTableSpec(relation);
    final ClassName className = makeClassName(field);
    final RelationSpec relationSpec = new RelationSpec(
            field, className, lTable, rTable, false);
    mCompileGraph.putRelationSpec(enclosingElement, relationSpec);
}
 
源代码11 项目: HighLite   文件: JavaWritableClass.java
Element findForeignKeyReferencedField(final Element enclosed,
                                      final ForeignKey foreignKey) {
    Element fieldRefElement = null;
    Element tableElem = mTypeUtils.asElement(enclosed.asType());
    for (final Element enc : getFields(tableElem)) {
        if (!enc.getSimpleName().toString().equals(foreignKey.fieldReference())) {
            continue;
        }

        final SQLiteColumn field = enc.getAnnotation(SQLiteColumn.class);
        if (field == null || (!field.primaryKey().enabled() && !field.unique())) {
            throw new ProcessingException(enclosed,
                    String.format("Field %s in class %s needs to be declared as primary key or "
                            + "unique with @SQLiteColumn to be referenced in "
                            + "@ForeignKey", enc.toString(), tableElem.toString()));
        }

        fieldRefElement = enc;
        break;
    }

    if (fieldRefElement == null) {
        throw new ProcessingException(enclosed,
                String.format("Field %s in class %s does not exist",
                        foreignKey.fieldReference(), tableElem.toString()));
    }

    return fieldRefElement;
}
 
源代码12 项目: litho   文件: DelegateMethodExtractor.java
private static List<Annotation> getMethodAnnotations(
    Element method, List<Class<? extends Annotation>> permittedMethodAnnotations) {
  List<Annotation> methodAnnotations = new ArrayList<>();
  for (Class<? extends Annotation> possibleDelegateMethodAnnotation :
      permittedMethodAnnotations) {
    final Annotation methodAnnotation = method.getAnnotation(possibleDelegateMethodAnnotation);
    if (methodAnnotation != null) {
      methodAnnotations.add(methodAnnotation);
    }
  }

  return methodAnnotations;
}
 
源代码13 项目: droitatedDB   文件: EntityAnnotationProcessor.java
private Persistence checkPersistenceAnnotation(final RoundEnvironment roundEnv) {
	Set<? extends Element> persistenceAnnotated = roundEnv.getElementsAnnotatedWith(Persistence.class);

	if (persistenceAnnotated.size() == 0) {
		return null;
	}

	if (persistenceAnnotated.size() > 1) {
		messager.printMessage(Kind.ERROR, "Only one @Persistence activator is allowed within the project", persistenceAnnotated.iterator().next());
		return null;
	}
	Element persistenceClass = persistenceAnnotated.iterator().next();
	return persistenceClass.getAnnotation(Persistence.class);
}
 
源代码14 项目: epoxy   文件: BaseModelAttributeInfo.java
BaseModelAttributeInfo(Element attribute, Types typeUtils, Elements elements,
    Logger logger, Memoizer memoizer) {
  this.typeUtils = typeUtils;
  this.setFieldName(attribute.getSimpleName().toString());
  setTypeMirror(attribute.asType(), memoizer);
  setJavaDocString(elements.getDocComment(attribute));

  classElement = (TypeElement) attribute.getEnclosingElement();
  setRootClass(classElement.getSimpleName().toString());
  setPackageName(elements.getPackageOf(classElement).getQualifiedName().toString());
  this.setHasSuperSetter(hasSuperMethod(classElement, attribute));
  this.setHasFinalModifier(attribute.getModifiers().contains(FINAL));
  this.setPackagePrivate(isFieldPackagePrivate(attribute));

  EpoxyAttribute annotation = attribute.getAnnotation(EpoxyAttribute.class);

  Set<Option> options = new HashSet<>(Arrays.asList(annotation.value()));
  validateAnnotationOptions(logger, annotation, options);

  //noinspection deprecation
  setUseInHash(annotation.hash() && !options.contains(Option.DoNotHash));
  setIgnoreRequireHashCode(options.contains(Option.IgnoreRequireHashCode));
  setDoNotUseInToString(options.contains(Option.DoNotUseInToString));

  //noinspection deprecation
  setGenerateSetter(annotation.setter() && !options.contains(Option.NoSetter));
  setGenerateGetter(!options.contains(Option.NoGetter));

  setPrivate(attribute.getModifiers().contains(PRIVATE));
  if (isPrivate()) {
    findGetterAndSetterForPrivateField(logger);
  }

  buildAnnotationLists(attribute.getAnnotationMirrors());
}
 
源代码15 项目: netbeans   文件: OpenUriHandlerProcessor.java
@Override
protected boolean handleProcess(
        Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) throws LayerGenerationException {

    for (Element e : roundEnv.getElementsAnnotatedWith(
            IntentHandlerRegistration.class)) {
        IntentHandlerRegistration r = e.getAnnotation(
                IntentHandlerRegistration.class);
        registerHandler(e, r);
    }
    return true;
}
 
源代码16 项目: barber   文件: Barbershop.java
private int resolveDefault(Element element) {
    StyledAttr styledAttr = element.getAnnotation(StyledAttr.class);
    if (styledAttr != null) {
        return styledAttr.defaultValue();
    }

    return -1;
}
 
源代码17 项目: zerocell   文件: ReaderTypeSpec.java
private Optional<String> checkRowNumberField() {
    for(Element element: typeElement.getEnclosedElements()) {
        if (! element.getKind().isField()) {
            continue;
        }
        RowNumber annotation = element.getAnnotation(RowNumber.class);
        if (! Objects.isNull(annotation)) {
            TypeMirror type;
            try {
                type = element.asType();
            } catch (MirroredTypeException mte) {
                type = mte.getTypeMirror();
            }
            final String fieldType = String.format("%s", type);
            final String fieldName = element.getSimpleName().toString();
            if (fieldType.equals(int.class.getTypeName())     ||
                fieldType.equals(long.class.getTypeName())    ||
                fieldType.equals(Integer.class.getTypeName()) ||
                fieldType.equals(Long.class.getTypeName())
            ) {
                return Optional.of(beanSetterPropertyName(fieldName));
            } else {
                // Must be one of the integer classes or bust!
                throw new IllegalArgumentException(
                        String.format("Invalid type (%s) for @RowNumber field (%s). Only java.lang.Integer and java.lang.Long are allowed", fieldType, fieldName));
            }
        }
    }
    return Optional.empty();
}
 
源代码18 项目: postman   文件: ParceledElementExtractor.java
private boolean hasParceledAnnotation(Element element) {
    return element.getAnnotation(Parceled.class) != null;
}
 
源代码19 项目: netbeans   文件: HTMLViewProcessor.java
@Override
    protected boolean handleProcess(Set<? extends TypeElement> set, RoundEnvironment re) throws LayerGenerationException {
        for (Element e : re.getElementsAnnotatedWith(OpenHTMLRegistration.class)) {
            OpenHTMLRegistration reg = e.getAnnotation(OpenHTMLRegistration.class);
            if (reg == null || e.getKind() != ElementKind.METHOD) {
                continue;
            }
            if (!e.getModifiers().contains(Modifier.STATIC)) {
                error("Method annotated by @OpenHTMLRegistration needs to be static", e);
            }
            if (!e.getModifiers().contains(Modifier.PUBLIC)) {
                error("Method annotated by @OpenHTMLRegistration needs to be public", e);
            }
            if (!((ExecutableElement)e).getParameters().isEmpty()) {
                error("Method annotated by @OpenHTMLRegistration should have no arguments", e);
            }
            if (!e.getEnclosingElement().getModifiers().contains(Modifier.PUBLIC)) {
                error("Method annotated by @OpenHTMLRegistration needs to be public in a public class", e);
            }
            
            ActionID aid = e.getAnnotation(ActionID.class);
            if (aid != null) {
                final LayerBuilder builder = layer(e);
                LayerBuilder.File actionFile = builder.
                        file("Actions/" + aid.category() + "/" + aid.id().replace('.', '-') + ".instance").
                        methodvalue("instanceCreate", "org.netbeans.modules.htmlui.Pages", "openAction");
                String abs = LayerBuilder.absolutizeResource(e, reg.url());
                try {
                    builder.validateResource(abs, e, reg, null, true);
                } catch (LayerGenerationException ex) {
                    if (System.getProperty("netbeans.home") != null) {
                        processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Cannot find resource " + abs, e);
                    } else {
                        throw ex;
                    }
                }
                actionFile.stringvalue("url", abs);
                if (!reg.iconBase().isEmpty()) {
                    actionFile.stringvalue("iconBase", reg.iconBase());
                }
                actionFile.stringvalue("method", e.getSimpleName().toString());
                actionFile.stringvalue("class", e.getEnclosingElement().asType().toString());
                String[] techIds = reg.techIds();
                for (int i = 0; i < techIds.length; i++) {
                    actionFile.stringvalue("techId." + i, techIds[i]);
                }
//                actionFile.instanceAttribute("component", TopComponent.class, reg, null);
//                if (reg.preferredID().length() > 0) {
//                    actionFile.stringvalue("preferredID", reg.preferredID());
//                }
                actionFile.bundlevalue("displayName", reg.displayName(), reg, "displayName");
                actionFile.write();
            } else {
                error("@OpenHTMLRegistration needs to be accompanied with @ActionID annotation", e);
            }
            
        }
        return true;
    }
 
源代码20 项目: HighLite   文件: SQLiteOpenHelperClass.java
private MethodSpec buildOnUpgradeMethod() {
    final CodeBlock.Builder onUpgradeStatements = CodeBlock.builder(),
            code = CodeBlock.builder();

    int onUpgradeCounter = 0;
    for (final Element enclosed : mElement.getEnclosedElements()) {
        if (enclosed.getAnnotation(OnUpgrade.class) == null) continue;

        if (++onUpgradeCounter > 1) {
            throw new ProcessingException(enclosed,
                    String.format("Only one method per class may be annotated with %s",
                            OnUpgrade.class.getCanonicalName()));
        }

        if (!enclosed.getModifiers().contains(Modifier.STATIC)) {
            throw new ProcessingException(enclosed,
                    String.format("%s annotated methods need to be static",
                            OnUpgrade.class.getCanonicalName()));
        }

        final ExecutableElement executableElement = (ExecutableElement) enclosed;
        if (executableElement.getParameters().size() != 3
                || !SQLITE_DATABASE.equals(
                ClassName.get(executableElement.getParameters().get(0).asType()))
                || !TypeName.INT.equals(
                ClassName.get(executableElement.getParameters().get(1).asType()))
                || !TypeName.INT.equals(
                ClassName.get(executableElement.getParameters().get(2).asType()))) {
            throw new ProcessingException(enclosed,
                    String.format("%s annotated methods needs to have exactly "
                                    + "three parameters, being of type %s, %s and %s "
                                    + "respectively",
                            OnUpgrade.class.getCanonicalName(),
                            SQLITE_DATABASE.toString(),
                            TypeName.INT.toString(),
                            TypeName.INT.toString()));
        }

        onUpgradeStatements.addStatement("$T.$L(database, oldVersion, newVersion)",
                ClassName.get(mElement.asType()), enclosed.getSimpleName());
    }

    for (final Map.Entry<Element, SQLiteTable> tableElementEntry
            : mTableElementMap.entrySet()) {

        code.addStatement("onUpgrade$L(database)", tableElementEntry.getKey().getSimpleName());
    }

    code.add(onUpgradeStatements.build());

    return MethodSpec.methodBuilder("onUpgrade")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(AnnotationSpec.builder(Override.class).build())
            .addParameter(SQLITE_DATABASE, "database", Modifier.FINAL)
            .addParameter(TypeName.INT, "oldVersion", Modifier.FINAL)
            .addParameter(TypeName.INT, "newVersion", Modifier.FINAL)
            .addCode(code.build())
            .build();
}