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 Project: Box   Author: lulululbj   File: AnnotationLister.java    License: 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 #2
Source Project: xtext-xtend   Author: eclipse   File: XtendValidator.java    License: 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 #3
Source Project: mPaaS   Author: lihangqi   File: ExtensionBuilder.java    License: 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 #4
Source Project: mPaaS   Author: lihangqi   File: ExtensionBuilder.java    License: 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 #5
Source Project: mPass   Author: tiankong0310   File: ExtensionBuilder.java    License: 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 #6
Source Project: mPass   Author: tiankong0310   File: ExtensionBuilder.java    License: 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 #7
@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 #8
Source Project: geowave   Author: locationtech   File: JavassistUtils.java    License: 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 #9
Source Project: development   Author: servicecatalog   File: CommandContextTest.java    License: 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 #10
Source Project: jetbrick-template-1x   Author: subchen   File: AnnotationClassReader.java    License: 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 #11
Source Project: smallrye-fault-tolerance   Author: smallrye   File: GenericConfig.java    License: 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 #12
Source Project: java-n-IDE-for-Android   Author: shenghuntianlang   File: AnnotationLister.java    License: 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 #13
Source Project: buck   Author: facebook   File: AnnotationLister.java    License: 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 #14
Source Project: j2objc   Author: google   File: ElementTypeTest.java    License: 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 #15
Source Project: netbeans   Author: apache   File: InterceptorBindingVerifier.java    License: 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 #16
Source Project: development   Author: servicecatalog   File: CommandContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEnumOptionalInvalid() {
    args.put("key", "CONSTRUCTOR");
    Set<ElementType> all = EnumSet.noneOf(ElementType.class);
    all.add(ElementType.FIELD);
    all.add(ElementType.METHOD);
    assertEquals(null, ctx.getEnumOptional("key", all));
}
 
Example #17
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: TargetAnnoCombo.java    License: 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 #18
Source Project: cxf   Author: apache   File: JAXBUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isJAXB22() {
    Target t = XmlElement.class.getAnnotation(Target.class);
    //JAXB 2.2 allows XmlElement on params.
    for (ElementType et : t.value()) {
        if (et == ElementType.PARAMETER) {
            return true;
        }
    }
    return false;
}
 
Example #19
Source Project: spotbugs   Author: spotbugs   File: UnresolvedXMethod.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ElementType getElementType() {
    if (Const.CONSTRUCTOR_NAME.equals(getName())) {
        return ElementType.CONSTRUCTOR;
    }
    return ElementType.METHOD;
}
 
Example #20
Source Project: openjdk-8-source   Author: keerath   File: TargetAnnoCombo.java    License: 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 #21
Source Project: hy.common.base   Author: HY-Org   File: ClassReflect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 从指定集合i_Classes中,挑出有注解的Class。并分类存储。
 * 
 * @param i_Classes          Java元类型的集合
 * @param i_AnnotationClass  注解类型的元类型
 * @return
 */
public static PartitionMap<ElementType ,ClassInfo> getAnnotations(List<Class<?>> i_Classes ,Class<? extends Annotation> i_AnnotationClass)
{
    PartitionMap<ElementType ,ClassInfo> v_Ret = new TablePartition<ElementType ,ClassInfo>();
    
    for (int i=0; i<i_Classes.size(); i++)
    {
        Class<?>  v_Class     = i_Classes.get(i);
        ClassInfo v_ClassInfo = new ClassInfo(v_Class);  // 为了在多个分区引用同一对象,所以在此无论是否被注解都new
        
        // 判断类是否注解
        if ( v_Class.isAnnotationPresent(i_AnnotationClass) )
        {
            v_Ret.putRow(ElementType.TYPE ,v_ClassInfo);
        }
        
        // 判断类中的自有方法是否注解
        List<Method> v_Methods = MethodReflect.getAnnotationMethods(v_Class ,i_AnnotationClass);
        if ( !Help.isNull(v_Methods) )
        {
            v_ClassInfo.setMethods(v_Methods);
            
            v_Ret.putRow(ElementType.METHOD ,v_ClassInfo);
        }
        
        // 判断类中的自有属性是否注解
        List<Field> v_Fields = getAnnotationFields(v_Class ,i_AnnotationClass);
        if ( !Help.isNull(v_Fields) )
        {
            v_ClassInfo.setFields(v_Fields);
            
            v_Ret.putRow(ElementType.FIELD ,v_ClassInfo);
        }
    }
    
    return v_Ret;
}
 
Example #22
Source Project: jfixture   Author: FlexTradeUKLtd   File: TestFixture.java    License: MIT License 5 votes vote down vote up
@Test
public void Annotation_can_only_be_applied_to_fields() {
    Target target = Fixture.class.getAnnotation(Target.class);
    assertEquals(1, target.value().length);
    ElementType type = target.value()[0];
    assertEquals(ElementType.FIELD, type);
}
 
Example #23
Source Project: auto   Author: google   File: PropertyAnnotationsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that when CopyAnnotationsToGeneratedField is present on a method, all non-inherited
 * annotations (except those appearing in CopyAnnotationsToGeneratedField.exclude) are copied to
 * the method implementation in the generated class.
 */
@Test
public void testCopyingMethodAnnotationsToGeneratedFields() {
  JavaFileObject inputFile =
      new InputFileBuilder()
          .setImports(getImports(PropertyAnnotationsTest.class, Target.class, ElementType.class))
          .addAnnotations(
              "@AutoValue.CopyAnnotations(exclude={PropertyAnnotationsTest."
                  + "TestAnnotation.class})",
              "@Deprecated",
              "@PropertyAnnotationsTest.TestAnnotation",
              "@PropertyAnnotationsTest.InheritedAnnotation",
              "@MethodsOnly")
          .addInnerTypes("@Target(ElementType.METHOD) @interface MethodsOnly {}")
          .build();

  JavaFileObject outputFile =
      new OutputFileBuilder()
          .setImports(getImports(PropertyAnnotationsTest.class))
          .addFieldAnnotations("@Deprecated", "@PropertyAnnotationsTest.InheritedAnnotation")
          .addMethodAnnotations(
              "@Deprecated",
              "@PropertyAnnotationsTest.InheritedAnnotation",
              "@Baz.MethodsOnly")
          .build();

  assertAbout(javaSource())
      .that(inputFile)
      .processedWith(new AutoValueProcessor())
      .compilesWithoutError()
      .and()
      .generatesSources(outputFile);
}
 
Example #24
Source Project: patchwork-api   Author: PatchworkMC   File: AnnotationStorage.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public Entry(
		String annotationType,
		ElementType targetType,
		String targetInClass,
		String target
) {
	this.annotationType = annotationType;
	this.targetType = targetType;
	this.targetInClass = targetInClass;
	this.target = target;
}
 
Example #25
Source Project: dolphin-platform   Author: canoo   File: ActionControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
/** Start ElementType Type Related Integration Test */

    @Test(dataProvider = ENDPOINTS_DATAPROVIDER, description = "Tests if an public action method with ElementType param can be called")
    public void testCallPublicMethodWithElementTypeParams(String containerType, String endpoint) {
        final ElementType value = ElementType.PARAMETER;
        performActionForElementType(containerType, endpoint, PUBLIC_WITH_ELEMENT_TYPE_PARAM_ACTION, value, new Param(PARAM_NAME, value));
    }
 
Example #26
Source Project: buck   Author: facebook   File: AnnotationLister.java    License: 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 #27
Source Project: openjdk-8-source   Author: keerath   File: TargetAnnoCombo.java    License: 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 #28
Source Project: openjdk-8   Author: bpupadhyaya   File: TargetAnnoCombo.java    License: 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 #29
Source Project: netbeans   Author: apache   File: TargetAnalyzer.java    License: 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 Project: openjdk-8   Author: bpupadhyaya   File: TargetAnnoCombo.java    License: 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;
}