当前位置: 首页>>代码示例>>Java>>正文


Java Element.getAnnotation方法代码示例

本文整理汇总了Java中javax.lang.model.element.Element.getAnnotation方法的典型用法代码示例。如果您正苦于以下问题:Java Element.getAnnotation方法的具体用法?Java Element.getAnnotation怎么用?Java Element.getAnnotation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.lang.model.element.Element的用法示例。


在下文中一共展示了Element.getAnnotation方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAllAnnotations

import javax.lang.model.element.Element; //导入方法依赖的package包/类
/**
 * 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()]);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:22,代码来源:InlineAnnotationReaderImpl.java

示例2: formatInterface

import javax.lang.model.element.Element; //导入方法依赖的package包/类
private static String formatInterface(Element iface, String format, Object... arguments) {
  final String immuName;

  if (null != iface.getAnnotation(SuperImmu.class)) {
    immuName = "@SuperImmu";
  } else {
    immuName = "@Immu";
  }

  return String.format(null, String.format((Locale) null, "%s interface %s %s", immuName, iface.getSimpleName(), format), arguments);
}
 
开发者ID:hf,项目名称:immu,代码行数:12,代码来源:ImmuValidationMessages.java

示例3: parseActivityView

import javax.lang.model.element.Element; //导入方法依赖的package包/类
private void parseActivityView(Element element,
                               Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
    //TODO print errors
    if (!SuperficialValidation.validateElement(element)) {
        error("Superficial validation error for %s", element.getSimpleName());
        return;
    }
    if (!Validator.isNotAbstractClass(element)) {
        error("%s is abstract", element.getSimpleName());
        return;
    }
    boolean isActivity =
            Validator.isSubType(element, ANDROID_ACTIVITY_CLASS_NAME, processingEnv);
    boolean isSupportActivity =
            Validator.isSubType(element, ANDROID_SUPPORT_ACTIVITY_CLASS_NAME, processingEnv);
    if (!isActivity && !isSupportActivity) {
        error("%s must extend Activity or AppCompatActivity", element.getSimpleName());
        return;
    }
    //getEnclosing for class type will returns its package/
    TypeElement enclosingElement = (TypeElement) element;
    DelegateClassGenerator delegateClassGenerator =
            getDelegate(enclosingElement, delegateClassMap);
    ActivityView annotation = element.getAnnotation(ActivityView.class);
    delegateClassGenerator.setResourceID(annotation.layout());
    if (isSupportActivity) {
        needSupportLoader = true;
        delegateClassGenerator.setViewType(ViewType.SUPPORT_ACTIVITY);
    } else {
        needLoader = true;
        delegateClassGenerator.setViewType(ViewType.ACTIVITY);
    }
    try {
        annotation.presenter();
    } catch (MirroredTypeException mte) {
        parsePresenter(delegateClassGenerator, mte);
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:39,代码来源:EasyMVPProcessor.java

示例4: parseFragmentView

import javax.lang.model.element.Element; //导入方法依赖的package包/类
private void parseFragmentView(Element element,
                               Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
    //TODO print errors
    if (!SuperficialValidation.validateElement(element)) {
        error("Superficial validation error for %s", element.getSimpleName());
        return;
    }
    if (!Validator.isNotAbstractClass(element)) {
        error("%s is abstract", element.getSimpleName());
        return;
    }
    boolean isFragment =
            Validator.isSubType(element, ANDROID_FRAGMENT_CLASS_NAME, processingEnv);
    boolean isSupportFragment =
            Validator.isSubType(element, ANDROID_SUPPORT_FRAGMENT_CLASS_NAME, processingEnv);
    if (!isFragment && !isSupportFragment) {
        error("%s must extend Fragment or support Fragment", element.getSimpleName());
        return;
    }
    //getEnclosing for class type will returns its package/
    TypeElement enclosingElement = (TypeElement) element;
    DelegateClassGenerator delegateClassGenerator =
            getDelegate(enclosingElement, delegateClassMap);
    if (isFragment) {
        needLoader = true;
        delegateClassGenerator.setViewType(ViewType.FRAGMENT);
    } else {
        needSupportLoader = true;
        delegateClassGenerator.setViewType(ViewType.SUPPORT_FRAGMENT);
    }
    FragmentView annotation = element.getAnnotation(FragmentView.class);
    try {
        annotation.presenter();
    } catch (MirroredTypeException mte) {
        parsePresenter(delegateClassGenerator, mte);
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:38,代码来源:EasyMVPProcessor.java

示例5: StyleableField

import javax.lang.model.element.Element; //导入方法依赖的package包/类
StyleableField(final Element element, final StyleableAnnotationValues annotationValues) {
    if (element == null || element.getAnnotation(Styleable.class) == null || element.getKind() != ElementKind.FIELD || element.getModifiers().contains(Modifier.PRIVATE)) {
        throw new IllegalArgumentException("Element parameter in StyleableField constructor must represent a non-private field annotated with the Styleable annotation");
    }

    final Styleable styleable = element.getAnnotation(Styleable.class);

    this.fieldName = element.getSimpleName().toString();
    this.typeName = TypeName.get(element.asType());
    this.styleableReference = annotationValues.getStyleableValue();
    this.defaultReference = annotationValues.getDefaultValue();
    this.hasDefaultValue = annotationValues.getDefaultValue() != null;
    this.styleableGroupName = annotationValues.getStyleableValue().getRClassName().packageName() + "." + annotationValues.getStyleableValue().getGroupName();

    for (final AnnotationMirror mirror : element.getAnnotationMirrors()) {
        String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString();

        if (annotationName.equals(COLOR_INT_CLASS_NAME)) {
            colorInt = true;
        } else if (annotationName.equals(DIMENSION_CLASS_NAME)) {
            dimension = true;

            for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : mirror.getElementValues().entrySet()) {
                if (entry.getKey().getSimpleName().contentEquals(DIMENSION_UNIT_FIELD_NAME)) {
                    int value = (int) entry.getValue().getValue();

                    if (value == 0) {
                        dimensionUnit = DimensionUnit.DP;
                    } else if (value == 1) {
                        dimensionUnit = DimensionUnit.PX;
                    } else if (value == 2) {
                        dimensionUnit = DimensionUnit.SP;
                    }
                }
            }
        }
    }
}
 
开发者ID:chRyNaN,项目名称:glimpse,代码行数:39,代码来源:StyleableField.java

示例6: collectElementsById

import javax.lang.model.element.Element; //导入方法依赖的package包/类
/**
 * Maps the elements in the supplied round environment to their IDs. The mappings are added to the {@link
 * AvatarRule#elementsById} map. Elements with no ID are ignored.
 *
 * @param roundEnvironment
 * 		contains the elements to map, not null
 */
private void collectElementsById(final RoundEnvironment roundEnvironment) {
	for (final Element e : roundEnvironment.getElementsAnnotatedWith(ElementId.class)) {
		final ElementId elementId = e.getAnnotation(ElementId.class);
		final String id = elementId.value();
		
		if (!elementsById.containsKey(id)) {
			elementsById.put(id, new HashSet<Element>());
		}
		
		elementsById.get(id).add(e);
	}
}
 
开发者ID:MatthewTamlin,项目名称:Avatar,代码行数:20,代码来源:AvatarRule.java

示例7: isAnnotatedWithClass

import javax.lang.model.element.Element; //导入方法依赖的package包/类
/**
 * check the annotation is illegal or not
 *
 * @param roundEnv
 * @param clazz    the annotation type
 * @return false if illegal
 */
private boolean isAnnotatedWithClass(RoundEnvironment roundEnv, Class<? extends Annotation> clazz) {
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(clazz);
    for (Element element : elements) {
        if (isValid(element)) {
            return false;
        }
        TypeElement typeElement = (TypeElement) element;
        String typeName = typeElement.getQualifiedName().toString();
        ProxyInfo info = map.get(typeName);
        if (info == null) {
            info = new ProxyInfo(mUtils, typeElement);
            map.put(typeName, info);
        }

        Annotation annotation = element.getAnnotation(clazz);
        if (annotation instanceof PermissionsRequestSync) {
            String[] permissions = ((PermissionsRequestSync) annotation).permission();
            int[] value = ((PermissionsRequestSync) annotation).value();
            if (permissions.length != value.length) {
                error(element, "permissions's length not equals value's length");
                return false;
            }
            info.syncPermissions.put(value, permissions);
        } else {
            error(element, "%s not support.", element);
            return false;
        }
    }

    return true;
}
 
开发者ID:jokermonn,项目名称:permissions4m,代码行数:39,代码来源:AnnotationProcessor.java

示例8: processJsonFieldAnnotation

import javax.lang.model.element.Element; //导入方法依赖的package包/类
private void processJsonFieldAnnotation(Element element, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements, Types types) {
    if (!isJsonFieldFieldAnnotationValid(element, elements)) {
        return;
    }

    TypeElement enclosingElement = (TypeElement)element.getEnclosingElement();

    JsonObjectHolder objectHolder = jsonObjectMap.get(TypeUtils.getInjectedFQCN(enclosingElement, elements));
    JsonFieldHolder fieldHolder = objectHolder.fieldMap.get(element.getSimpleName().toString());

    if (fieldHolder == null) {
        fieldHolder = new JsonFieldHolder();
        objectHolder.fieldMap.put(element.getSimpleName().toString(), fieldHolder);
    }

    JsonField annotation = element.getAnnotation(JsonField.class);

    TypeMirror typeConverterType;
    try {
        typeConverterType = mProcessingEnv.getElementUtils().getTypeElement(annotation.typeConverter().getCanonicalName()).asType();
    } catch (MirroredTypeException mte) {
        typeConverterType = mte.getTypeMirror();
    }

    String[] fieldName = annotation.name();

    JsonIgnore ignoreAnnotation = element.getAnnotation(JsonIgnore.class);
    boolean shouldParse = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.SERIALIZE_ONLY;
    boolean shouldSerialize = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.PARSE_ONLY;

    String error = fieldHolder.fill(element, elements, types, fieldName, typeConverterType, objectHolder, shouldParse, shouldSerialize);
    if (!TextUtils.isEmpty(error)) {
        error(element, error);
    }

    ensureTypeConverterClassValid(typeConverterType, elements, types);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:38,代码来源:JsonFieldProcessor.java

示例9: process

import javax.lang.model.element.Element; //导入方法依赖的package包/类
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }

    Element globalConfigElement = null;
    try {
        globalConfigElement = prepareGlobalConfig(roundEnv);
        SqlFirstApcConfig globalConfig = globalConfigElement.getAnnotation(SqlFirstApcConfig.class);
        List<DaoDesc> daoDescList = processSqlSource(roundEnv, globalConfig);

        if (globalConfig != null) {
            prepareDaoClassImplementMap(daoDescList, roundEnv);
            DaoWriter daoWriter = new DaoWriter(processingEnv);
            daoWriter.write(daoDescList, globalConfig);
        }
        return !daoDescList.isEmpty();
    
    } catch (RuntimeException ex) {
        if (globalConfigElement == null) {
            roundEnv.getElementsAnnotatedWith(SqlSource.class).forEach(x ->
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getFullStackTrace(ex), x)
            );
        } else {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getFullStackTrace(ex), globalConfigElement);
    
        }
    }
    return false;
}
 
开发者ID:nds842,项目名称:sql-first-mapper,代码行数:32,代码来源:SqlFirstAnnotationProcessor.java

示例10: processReference

import javax.lang.model.element.Element; //导入方法依赖的package包/类
private void processReference(ScopeReference ar, Element annotated, LayerBuilder builder) {
    String id = ar.id();
    if (id.isEmpty()) {
        ScopeProvider.Registration desc = annotated.getAnnotation(ScopeProvider.Registration.class);
        if (desc == null) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ERR_ID_NEEDED, annotated);
        } else {
            id = desc.id();
        }
    }
    LayerBuilder.File f = builder.file("Scopes/" + ar.path() + "/" + id + ".shadow");
    f.stringvalue("originalFile", "Scopes/ScopeDescriptions/" + id + ".instance");
    f.write();
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:15,代码来源:ScopeAnnotationProcessor.java

示例11: handleProcess

import javax.lang.model.element.Element; //导入方法依赖的package包/类
@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;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:14,代码来源:OpenUriHandlerProcessor.java

示例12: checkForInvalidImplAnnotation

import javax.lang.model.element.Element; //导入方法依赖的package包/类
protected void checkForInvalidImplAnnotation(Element element, Class annotationClass) {
    Object annotation = element.getAnnotation(annotationClass);
    if (annotation != null) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTEFACE_PLUS_ANNOTATION(annotationClass.getName()), element);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:7,代码来源:WebServiceVisitor.java

示例13: process

import javax.lang.model.element.Element; //导入方法依赖的package包/类
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
    for(final Element element : environment.getElementsAnnotatedWith(PutMany.class)) {
        final PutMany annotation = element.getAnnotation(PutMany.class);

        if(ElementKind.METHOD != element.getKind()) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not a method.");
        }

        final Set<Modifier> modifiers = element.getModifiers();
        if(!modifiers.contains(Modifier.PUBLIC)) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with public methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not public.");
        }
        if(modifiers.contains(Modifier.STATIC)) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with non-static methods only! Tried to use with " + element.getSimpleName()
                    + ", which is static.");
        }

        final ExecutableType method = (ExecutableType)element.asType();
        final Types types = processingEnv.getTypeUtils();
        final Elements elements = processingEnv.getElementUtils();

        // annotation.value() will throw the exception because it doesn't have compiled class information yet, and is of type Class<?>.
        TypeMirror annotatedType = null;
        try {
            annotation.value();
        } catch(final MirroredTypeException e) {
            annotatedType = e.getTypeMirror();
        }

        if(TypeKind.VOID != method.getReturnType().getKind()) {
            throw new DataSinkDefinitionException("@PutMany method must have void return! Tried to use with " + element.getSimpleName() + ", which returns "
                + method.getReturnType() + ".");
        }
        if(method.getParameterTypes().size() != 2) {
            throw new DataSinkDefinitionException("@PutMany methods must take 2 arguments: Iterable<T> items, PipelineContext context. Tried to use with "
                + element.getSimpleName() + ", which has a different signature.");
        }

        final TypeElement iterableType = elements.getTypeElement(Iterable.class.getName());
        final TypeMirror[] genericType = new TypeMirror[] {annotatedType};
        final DeclaredType itemsType = types.getDeclaredType(iterableType, genericType);
        final TypeMirror contextType = elements.getTypeElement(PipelineContext.class.getName()).asType();

        if(!types.isAssignable(itemsType, method.getParameterTypes().get(0))) {
            throw new DataSinkDefinitionException(
                "@PutMany method annotated value must be assignable from the generic type of the method's first argument . Tried to use with "
                    + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(0) + ".");
        }
        if(!types.isAssignable(method.getParameterTypes().get(1), contextType)) {
            throw new DataSinkDefinitionException("@PutMany method second argument must be assignable from " + contextType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(1) + ".");
        }
    }

    return true;
}
 
开发者ID:meraki-analytics,项目名称:datapipelines-java,代码行数:63,代码来源:PutManyProcessor.java

示例14: processEvents

import javax.lang.model.element.Element; //导入方法依赖的package包/类
private void processEvents(ComponentInfo componentInfo,
                           Element componentElement) {
  for (Element element : componentElement.getEnclosedElements()) {
    if (!isPublicMethod(element)) {
      continue;
    }

    // Get the name of the prospective event.
    String eventName = element.getSimpleName().toString();
    SimpleEvent simpleEventAnnotation = element.getAnnotation(SimpleEvent.class);

    // Remove overriden events unless SimpleEvent is again specified.
    // See comment in processProperties for an example.
    if (simpleEventAnnotation == null) {
      if (componentInfo.events.containsKey(eventName)) {
        componentInfo.events.remove(eventName);
      }
    } else {
      String eventDescription = simpleEventAnnotation.description();
      if (eventDescription.isEmpty()) {
        eventDescription = elementUtils.getDocComment(element);
        if (eventDescription == null) {
          messager.printMessage(Diagnostic.Kind.WARNING,
                                "In component " + componentInfo.name +
                                ", event " + eventName +
                                " is missing a description.");
          eventDescription = "";
        }
      }
      boolean userVisible = simpleEventAnnotation.userVisible();
      boolean deprecated = elementUtils.isDeprecated(element);
      Event event = new Event(eventName, eventDescription, userVisible, deprecated);
      componentInfo.events.put(event.name, event);

      // Verify that this element has an ExecutableType.
      if (!(element instanceof ExecutableElement)) {
        throw new RuntimeException("In component " + componentInfo.name +
                                   ", the representation of SimpleEvent " + eventName +
                                   " does not implement ExecutableElement.");
      }
      ExecutableElement e = (ExecutableElement) element;

      // Extract the parameters.
      for (VariableElement ve : e.getParameters()) {
        event.addParameter(ve.getSimpleName().toString(),
                           ve.asType().toString());
      }
    }
  }
}
 
开发者ID:mit-cml,项目名称:appinventor-extensions,代码行数:51,代码来源:ComponentProcessor.java

示例15: ComponentInfo

import javax.lang.model.element.Element; //导入方法依赖的package包/类
protected ComponentInfo(Element element) {
  super(element.getSimpleName().toString(),  // Short name
        elementUtils.getDocComment(element),
        "Component");
  type = element.asType().toString();
  displayName = getDisplayNameForComponentType(name);
  permissions = Sets.newHashSet();
  libraries = Sets.newHashSet();
  nativeLibraries = Sets.newHashSet();
  assets = Sets.newHashSet();
  activities = Sets.newHashSet();
  broadcastReceivers = Sets.newHashSet();
  classNameAndActionsBR = Sets.newHashSet();
  designerProperties = Maps.newTreeMap();
  properties = Maps.newTreeMap();
  methods = Maps.newTreeMap();
  events = Maps.newTreeMap();
  abstractClass = element.getModifiers().contains(Modifier.ABSTRACT);
  external = false;
  for (AnnotationMirror am : element.getAnnotationMirrors()) {
    DeclaredType dt = am.getAnnotationType();
    String annotationName = am.getAnnotationType().toString();
    if (annotationName.equals(SimpleObject.class.getName())) {
      simpleObject = true;
      SimpleObject simpleObjectAnnotation = element.getAnnotation(SimpleObject.class);
      external = simpleObjectAnnotation.external();
    }
    if (annotationName.equals(DesignerComponent.class.getName())) {
      designerComponent = true;
      DesignerComponent designerComponentAnnotation =
          element.getAnnotation(DesignerComponent.class);

      // Override javadoc description with explicit description
      // if provided.
      String explicitDescription = designerComponentAnnotation.description();
      if (!explicitDescription.isEmpty()) {
        description = explicitDescription;
      }

      // Set helpDescription to the designerHelpDescription field if
      // provided; otherwise, use description
      helpDescription = designerComponentAnnotation.designerHelpDescription();
      if (helpDescription.isEmpty()) {
        helpDescription = description;
      }
      helpUrl = designerComponentAnnotation.helpUrl();
      if (!helpUrl.startsWith("http:") && !helpUrl.startsWith("https:")) {
        helpUrl = "";  // only accept http: or https: URLs (e.g., no javascript:)
      }

      category = designerComponentAnnotation.category().getName();
      categoryString = designerComponentAnnotation.category().toString();
      version = designerComponentAnnotation.version();
      showOnPalette = designerComponentAnnotation.showOnPalette();
      nonVisible = designerComponentAnnotation.nonVisible();
      iconName = designerComponentAnnotation.iconName();
    }
  }
}
 
开发者ID:mit-cml,项目名称:appinventor-extensions,代码行数:60,代码来源:ComponentProcessor.java


注:本文中的javax.lang.model.element.Element.getAnnotation方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。