java.lang.annotation.ElementType Java Examples

The following examples show how to use java.lang.annotation.ElementType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExtensionBuilder.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 从本地的Json文件加载
 */
public static ExtensionImpl newExtension(ExtensionPointImpl point,
                                         Class<?> clazz, Member member, JSONObject json)
        throws ReflectiveOperationException {
    ExtensionImpl extension = new ExtensionImpl();
    if (json != null) {
        extension.setConfig(json);
    }
    extension.setPoint(point);
    extension.setRefClass(clazz);
    extension.setElementName(member.getName());
    extension.setElementType(member instanceof Method ? ElementType.METHOD
            : ElementType.FIELD);
    // 校验、补全
    validate(extension);
    format(extension);
    return extension;
}
 
Example #2
Source File: TypeDescriptionGenericVisitorValidatorForTypeAnnotations.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(otherLegal.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(true);
    when(otherIllegal.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(false);
    when(illegal.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(illegalAnnotation));
    when(illegalAnnotation.getElementTypes()).thenReturn(new HashSet<ElementType>());
    when(illegalAnnotation.getAnnotationType()).thenReturn(illegalType);
    when(otherLegal.asGenericType()).thenReturn(otherLegal);
    when(otherIllegal.asGenericType()).thenReturn(otherIllegal);
    try {
        Enum<?> typeUse = Enum.valueOf(ElementType.class, "TYPE_USE");
        Enum<?> typeParameter = Enum.valueOf(ElementType.class, "TYPE_PARAMETER");
        when(legalAnnotation.getElementTypes()).thenReturn(new HashSet(Arrays.asList(typeUse, typeParameter)));
        when(duplicateAnnotation.getElementTypes()).thenReturn(new HashSet(Arrays.asList(typeUse, typeParameter)));
    } catch (IllegalArgumentException ignored) {
        when(legalAnnotation.getElementTypes()).thenReturn(Collections.<ElementType>emptySet());
        when(duplicateAnnotation.getElementTypes()).thenReturn(Collections.<ElementType>emptySet());
    }
    when(legal.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(legalAnnotation));
    when(duplicate.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(legalAnnotation, duplicateAnnotation));
    when(legalAnnotation.getAnnotationType()).thenReturn(legalType);
    when(duplicateAnnotation.getAnnotationType()).thenReturn(legalType);
}
 
Example #3
Source File: ElementTypeTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 * @tests java.lang.annotation.ElementType#valueOf(String)
 */
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
    assertSame(ElementType.ANNOTATION_TYPE, ElementType
            .valueOf("ANNOTATION_TYPE"));
    assertSame(ElementType.CONSTRUCTOR, ElementType.valueOf("CONSTRUCTOR"));
    assertSame(ElementType.FIELD, ElementType.valueOf("FIELD"));
    assertSame(ElementType.LOCAL_VARIABLE, ElementType
            .valueOf("LOCAL_VARIABLE"));
    assertSame(ElementType.METHOD, ElementType.valueOf("METHOD"));
    assertSame(ElementType.PACKAGE, ElementType.valueOf("PACKAGE"));
    assertSame(ElementType.PARAMETER, ElementType.valueOf("PARAMETER"));
    assertSame(ElementType.TYPE, ElementType.valueOf("TYPE"));
    try {
        ElementType.valueOf("OTHER");
        fail("Should throw an IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
 
Example #4
Source File: InterceptorBindingVerifier.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasReqiredTarget( AnnotationMirror target , Set<ElementType>
    targetTypes ) 
{
    int sz = 1;
    if(targetTypes.size()>0){
        sz = targetTypes.size();
        if(targetTypes.contains( ElementType.TYPE)){
            sz--;
        }
        if ( targetTypes.contains( ElementType.METHOD)) {
            sz--;
        }
        if (targetTypes.contains( ElementType.CONSTRUCTOR) )
        {
            sz--;
        }
    }
    return sz==0;
}
 
Example #5
Source File: ExtensionBuilder.java    From mPass with Apache License 2.0 6 votes vote down vote up
/**
 * 从注解加载
 */
public static ExtensionImpl newExtension(ExtensionPointImpl point,
                                         Class<?> clazz, Annotation annotation)
        throws ReflectiveOperationException {
    ExtensionImpl extension = new ExtensionImpl();
    JSONObject json = PluginReflectUtil.annotationToJson(annotation);
    if (point.getConfig() != null) {
        extension.setConfig(json);
    }
    extension.setPoint(point);
    extension.setRefClass(clazz);
    extension.setElementType(ElementType.TYPE);
    // 校验、补全
    validate(extension);
    format(extension);
    return extension;
}
 
Example #6
Source File: ExtensionBuilder.java    From mPass with Apache License 2.0 6 votes vote down vote up
/**
 * 从本地的Json文件加载
 */
public static ExtensionImpl newExtension(ExtensionPointImpl point,
                                         Class<?> clazz, JSONObject json)
        throws ReflectiveOperationException {
    ExtensionImpl extension = new ExtensionImpl();
    if (json != null) {
        extension.setConfig(json);
    }
    extension.setPoint(point);
    extension.setRefClass(clazz);
    extension.setElementType(ElementType.TYPE);
    // 校验、补全
    validate(extension);
    format(extension);
    return extension;
}
 
Example #7
Source File: CommandContextTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetEnumInvalid() {
    args.put("key", "CONSTRUCTOR");
    Set<ElementType> all = EnumSet.noneOf(ElementType.class);
    all.add(ElementType.FIELD);
    all.add(ElementType.METHOD);
    System.out.print(all);
    try {
        ctx.getEnum("key", all);
        fail("IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
        assertEquals(
                "Invalid parameter value 'CONSTRUCTOR' for key. Valid values are [FIELD, METHOD].",
                e.getMessage());
    }
}
 
Example #8
Source File: AnnotationClassReader.java    From jetbrick-template-1x with Apache License 2.0 6 votes vote down vote up
private boolean readAttributes(DataInput di, ElementType type) throws IOException {
    final int count = di.readUnsignedShort();

    for (int i = 0; i < count; ++i) {
        final String name = resolveUtf8(di);
        // in bytes, use this to skip the attribute info block
        final int length = di.readInt();

        if (type == ElementType.TYPE && ("RuntimeVisibleAnnotations".equals(name) || "RuntimeInvisibleAnnotations".equals(name))) {
            if (readAnnotations(di)) {
                return true;
            }
        } else {
            di.skipBytes(length);
        }
    }
    return false;
}
 
Example #9
Source File: ExtensionBuilder.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 从注解加载
 */
public static ExtensionImpl newExtension(ExtensionPointImpl point,
                                         Class<?> clazz, Member member, Annotation annotation)
        throws ReflectiveOperationException {
    ExtensionImpl extension = new ExtensionImpl();
    JSONObject json = PluginReflectUtil.annotationToJson(annotation);
    if (point.getConfig() != null) {
        extension.setConfig(json);
    }
    extension.setPoint(point);
    extension.setRefClass(clazz);
    extension.setElementName(member.getName());
    extension.setElementType(member instanceof Method ? ElementType.METHOD
            : ElementType.FIELD);
    // 校验、补全
    validate(extension);
    format(extension);
    return extension;
}
 
Example #10
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkAnnotationTarget(XAnnotation annotation) {
	JvmType annotationType = annotation.getAnnotationType();
	if (annotationType == null || annotationType.eIsProxy() || !(annotationType instanceof JvmAnnotationType)) {
		return;
	}
	Set<ElementType> targets = annotationUtil.getAnnotationTargets((JvmAnnotationType) annotationType);
	if (targets.isEmpty())
		return;
	final EObject eContainer = getContainingAnnotationTarget(annotation);
	Class<? extends EObject> clazz = eContainer.getClass();
	if (eContainer instanceof XtendField && eContainer.eContainer() instanceof XtendAnnotationType) {
		clazz = XtendFunction.class;
	}
	for (Entry<Class<?>, Collection<ElementType>> mapping : targetInfos.asMap().entrySet()) {
		if (mapping.getKey().isAssignableFrom(clazz)) {
			targets.retainAll(mapping.getValue());
			if (targets.isEmpty()) {
				error("The annotation @" + annotation.getAnnotationType().getSimpleName()
						+ " is disallowed for this location.", annotation, null, INSIGNIFICANT_INDEX,
						ANNOTATION_WRONG_TARGET);
			}
		}
	}
}
 
Example #11
Source File: AnnotationLister.java    From Box with Apache License 2.0 6 votes vote down vote up
/**
 * Inspects a class annotation.
 *
 * @param cf {@code non-null;} class file
 * @param ann {@code non-null;} annotation
 */
private void visitClassAnnotation(DirectClassFile cf,
        BaseAnnotations ann) {

    if (!args.eTypes.contains(ElementType.TYPE)) {
        return;
    }

    for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
        String annClassName
                = anAnn.getType().getClassType().getClassName();
        if (args.aclass.equals(annClassName)) {
            printMatch(cf);
        }
    }
}
 
Example #12
Source File: GenericConfig.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
/**
 * Note that:
 *
 * <pre>
 * If no annotation matches the specified parameter, the property will be ignored.
 * </pre>
 *
 * @param key
 * @param expectedType
 * @return the configured value
 */
private <U> U lookup(String key, Class<U> expectedType) {
    Config config = getConfig();
    Optional<U> value;
    if (ElementType.METHOD.equals(annotationSource)) {
        // <classname>/<methodname>/<annotation>/<parameter>
        value = config.getOptionalValue(getConfigKeyForMethod() + key, expectedType);
    } else {
        // <classname>/<annotation>/<parameter>
        value = config.getOptionalValue(getConfigKeyForClass() + key, expectedType);
    }
    if (!value.isPresent()) {
        // <annotation>/<parameter>
        value = config.getOptionalValue(annotationType.getSimpleName() + "/" + key, expectedType);
    }
    // annotation values
    return value.orElseGet(() -> getConfigFromAnnotation(key));
}
 
Example #13
Source File: JavassistUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Simple helper method to essentially clone the annotations from one class onto another.
 */
public static void copyClassAnnotations(final CtClass oldClass, final CtClass newClass) {
  // Load the existing annotations attributes
  final AnnotationsAttribute classAnnotations =
      (AnnotationsAttribute) oldClass.getClassFile().getAttribute(
          AnnotationsAttribute.visibleTag);

  // Clone them
  final AnnotationsAttribute copyClassAttribute =
      JavassistUtils.cloneAnnotationsAttribute(
          newClass.getClassFile2().getConstPool(),
          classAnnotations,
          ElementType.TYPE);

  // Set the annotations on the new class
  newClass.getClassFile().addAttribute(copyClassAttribute);
}
 
Example #14
Source File: AnnotationLister.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Inspects a class annotation.
 *
 * @param cf {@code non-null;} class file
 * @param ann {@code non-null;} annotation
 */
private void visitClassAnnotation(DirectClassFile cf,
        BaseAnnotations ann) {

    if (!args.eTypes.contains(ElementType.TYPE)) {
        return;
    }

    for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
        String annClassName
                = anAnn.getType().getClassType().getClassName();
        if (args.aclass.equals(annClassName)) {
            printMatch(cf);
        }
    }
}
 
Example #15
Source File: AnnotationLister.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Inspects a class annotation.
 *
 * @param cf {@code non-null;} class file
 * @param ann {@code non-null;} annotation
 */
private void visitClassAnnotation(DirectClassFile cf,
        BaseAnnotations ann) {

    if (!args.eTypes.contains(ElementType.TYPE)) {
        return;
    }

    for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
        String annClassName
                = anAnn.getType().getClassType().getClassName();
        if (args.aclass.equals(annClassName)) {
            printMatch(cf);
        }
    }
}
 
Example #16
Source File: TargetAnnoCombo.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private Set<ElementType> less(Set<ElementType> base, ElementType... sub) {
    Set<ElementType> res = EnumSet.noneOf(ElementType.class);
    res.addAll(base);
    for (ElementType t : sub) {
        res.remove(t);
    }
    return res;
}
 
Example #17
Source File: AnnotationLister.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Inspects a package annotation
 *
 * @param cf {@code non-null;} class file of "package-info" pseudo-class
 * @param ann {@code non-null;} annotation
 */
private void visitPackageAnnotation(
        DirectClassFile cf, BaseAnnotations ann) {

    if (!args.eTypes.contains(ElementType.PACKAGE)) {
        return;
    }

    String packageName = cf.getThisClass().getClassType().getClassName();

    int slashIndex = packageName.lastIndexOf('/');

    if (slashIndex == -1) {
        packageName = "";
    } else {
        packageName
                = packageName.substring(0, slashIndex);
    }


    for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
        String annClassName
                = anAnn.getType().getClassType().getClassName();
        if (args.aclass.equals(annClassName)) {
            printMatchPackage(packageName);
        }
    }
}
 
Example #18
Source File: Util.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test whether the given FieldDoc is one of the declaration annotation ElementTypes
 * defined in Java 5.
 * Instead of testing for one of the new enum constants added in Java 8, test for
 * the old constants. This prevents bootstrapping problems.
 *
 * @param elt The FieldDoc to test
 * @return true, iff the given ElementType is one of the constants defined in Java 5
 * @since 1.8
 */
public static boolean isJava5DeclarationElementType(FieldDoc elt) {
    return elt.name().contentEquals(ElementType.ANNOTATION_TYPE.name()) ||
            elt.name().contentEquals(ElementType.CONSTRUCTOR.name()) ||
            elt.name().contentEquals(ElementType.FIELD.name()) ||
            elt.name().contentEquals(ElementType.LOCAL_VARIABLE.name()) ||
            elt.name().contentEquals(ElementType.METHOD.name()) ||
            elt.name().contentEquals(ElementType.PACKAGE.name()) ||
            elt.name().contentEquals(ElementType.PARAMETER.name()) ||
            elt.name().contentEquals(ElementType.TYPE.name());
}
 
Example #19
Source File: TargetAnnoCombo.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private List<String> convertToString(Set<ElementType> annoTarget) {
    if (annoTarget == null) {
        return null;
    }
    List<String> annoTargets = new ArrayList<String>();
    for (ElementType e : annoTarget) {
        annoTargets.add("ElementType." + e.name());
    }
    return annoTargets;
}
 
Example #20
Source File: BaseModelAttributeInfo.java    From epoxy with Apache License 2.0 5 votes vote down vote up
/**
 * Keeps track of annotations on the attribute so that they can be used in the generated setter
 * and getter method. Setter and getter annotations are stored separately since the annotation may
 * not target both method and parameter types.
 */
private void buildAnnotationLists(List<? extends AnnotationMirror> annotationMirrors) {
  for (AnnotationMirror annotationMirror : annotationMirrors) {
    if (!annotationMirror.getElementValues().isEmpty()) {
      // Not supporting annotations with values for now
      continue;
    }

    ClassName annotationClass =
        ClassName.bestGuess(annotationMirror.getAnnotationType().toString());
    if (annotationClass.equals(ClassName.get(EpoxyAttribute.class))) {
      // Don't include our own annotation
      continue;
    }

    DeclaredType annotationType = annotationMirror.getAnnotationType();
    // A target may exist on an annotation type to specify where the annotation can
    // be used, for example fields, methods, or parameters.
    Target targetAnnotation = annotationType.asElement().getAnnotation(Target.class);

    // Allow all target types if no target was specified on the annotation
    List<ElementType> elementTypes =
        Arrays.asList(targetAnnotation == null ? ElementType.values() : targetAnnotation.value());

    AnnotationSpec annotationSpec = AnnotationSpec.builder(annotationClass).build();
    if (elementTypes.contains(ElementType.PARAMETER)) {
      getSetterAnnotations().add(annotationSpec);
    }

    if (elementTypes.contains(ElementType.METHOD)) {
      getGetterAnnotations().add(annotationSpec);
    }
  }
}
 
Example #21
Source File: TargetAnnoCombo.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private List<String> convertToString(Set<ElementType> annoTarget) {
    if (annoTarget == null) {
        return null;
    }
    List<String> annoTargets = new ArrayList<String>();
    for (ElementType e : annoTarget) {
        annoTargets.add("ElementType." + e.name());
    }
    return annoTargets;
}
 
Example #22
Source File: TargetAnnoCombo.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private Set<ElementType> less(Set<ElementType> base, ElementType... sub) {
    Set<ElementType> res = EnumSet.noneOf(ElementType.class);
    res.addAll(base);
    for (ElementType t : sub) {
        res.remove(t);
    }
    return res;
}
 
Example #23
Source File: TargetAnnoCombo.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private List<String> convertToString(Set<ElementType> annoTarget) {
    if (annoTarget == null) {
        return null;
    }
    List<String> annoTargets = new ArrayList<String>();
    for (ElementType e : annoTarget) {
        annoTargets.add("ElementType." + e.name());
    }
    return annoTargets;
}
 
Example #24
Source File: TargetAnnoCombo.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private Set<ElementType> plus(Set<ElementType> base, ElementType... add) {
    Set<ElementType> res = EnumSet.noneOf(ElementType.class);
    res.addAll(base);
    for (ElementType t : add) {
        res.add(t);
    }
    return res;
}
 
Example #25
Source File: Util.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test whether the given FieldDoc is one of the declaration annotation ElementTypes
 * defined in Java 5.
 * Instead of testing for one of the new enum constants added in Java 8, test for
 * the old constants. This prevents bootstrapping problems.
 *
 * @param elt The FieldDoc to test
 * @return true, iff the given ElementType is one of the constants defined in Java 5
 * @since 1.8
 */
public static boolean isJava5DeclarationElementType(FieldDoc elt) {
    return elt.name().contentEquals(ElementType.ANNOTATION_TYPE.name()) ||
            elt.name().contentEquals(ElementType.CONSTRUCTOR.name()) ||
            elt.name().contentEquals(ElementType.FIELD.name()) ||
            elt.name().contentEquals(ElementType.LOCAL_VARIABLE.name()) ||
            elt.name().contentEquals(ElementType.METHOD.name()) ||
            elt.name().contentEquals(ElementType.PACKAGE.name()) ||
            elt.name().contentEquals(ElementType.PARAMETER.name()) ||
            elt.name().contentEquals(ElementType.TYPE.name());
}
 
Example #26
Source File: ClassInfo.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ElementType getElementType() {
    if (getClassName().endsWith("package-info")) {
        return ElementType.PACKAGE;
    } else if (isAnnotation()) {
        return ElementType.ANNOTATION_TYPE;
    }
    return ElementType.TYPE;

}
 
Example #27
Source File: TargetAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Set<ElementType> getDeclaredTargetTypes(
        AnnotationHelper helper, AnnotationMirror target)
{
    AnnotationParser parser = AnnotationParser.create(helper);
    final Set<String> elementTypes = new HashSet<String>();
    parser.expectEnumConstantArray( AnnotationUtil.VALUE, 
            helper.resolveType(
            ElementType.class.getCanonicalName()), 
            new ArrayValueHandler() {
                
                @Override
                public Object handleArray( List<AnnotationValue> arrayMembers ) {
                    for (AnnotationValue arrayMember : arrayMembers) {
                        String value = arrayMember.getValue().toString();
                        elementTypes.add(value);
                    }
                    return null;
                }
            } , null);
    
    parser.parse( target );
    Set<ElementType> result = new HashSet<ElementType>();
    for (String type : elementTypes) {
        ElementType elementType = ElementType.valueOf(ElementType.class, type);
        result.add( elementType );
    }
    return result;
}
 
Example #28
Source File: TargetAnnoCombo.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private Set<ElementType> plus(Set<ElementType> base, ElementType... add) {
    Set<ElementType> res = EnumSet.noneOf(ElementType.class);
    res.addAll(base);
    for (ElementType t : add) {
        res.add(t);
    }
    return res;
}
 
Example #29
Source File: TargetAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Set<ElementType> getDeclaredTargetTypes( 
        AnnotationHelper helper, TypeElement element ) 
{
    Map<String, ? extends AnnotationMirror> types = helper
            .getAnnotationsByType(element.getAnnotationMirrors());
    AnnotationMirror target = types.get(Target.class.getCanonicalName());
    if (target == null) {
        return Collections.emptySet();
    }
    return getDeclaredTargetTypes( helper, target );
}
 
Example #30
Source File: Util.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test whether the given FieldDoc is one of the declaration annotation ElementTypes
 * defined in Java 5.
 * Instead of testing for one of the new enum constants added in Java 8, test for
 * the old constants. This prevents bootstrapping problems.
 *
 * @param elt The FieldDoc to test
 * @return true, iff the given ElementType is one of the constants defined in Java 5
 * @since 1.8
 */
public static boolean isJava5DeclarationElementType(FieldDoc elt) {
    return elt.name().contentEquals(ElementType.ANNOTATION_TYPE.name()) ||
            elt.name().contentEquals(ElementType.CONSTRUCTOR.name()) ||
            elt.name().contentEquals(ElementType.FIELD.name()) ||
            elt.name().contentEquals(ElementType.LOCAL_VARIABLE.name()) ||
            elt.name().contentEquals(ElementType.METHOD.name()) ||
            elt.name().contentEquals(ElementType.PACKAGE.name()) ||
            elt.name().contentEquals(ElementType.PARAMETER.name()) ||
            elt.name().contentEquals(ElementType.TYPE.name());
}