java.lang.annotation.Target Java Examples

The following examples show how to use java.lang.annotation.Target. 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: Annotations.java    From immutables with Apache License 2.0 6 votes vote down vote up
static boolean annotationMatchesTarget(Element annotationElement, ElementType elementType) {
  @Nullable Target target = annotationElement.getAnnotation(Target.class);
  if (target != null) {
    ElementType[] targetTypes = target.value();
    if (targetTypes.length == 0) {
      return false;
    }
    boolean found = false;
    for (ElementType t : targetTypes) {
      if (t == elementType) {
        found = true;
      }
    }
    if (!found) {
      return false;
    }
  }
  return true;
}
 
Example #2
Source File: SimpleMethodSignatureOffsetMappingFactory.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Override
public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target,
                                 AnnotationDescription.Loadable<SimpleMethodSignature> annotation,
                                 AdviceType adviceType) {
    return new Advice.OffsetMapping() {
        @Override
        public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner,
                              Advice.ArgumentHandler argumentHandler, Sort sort) {
            final String className = instrumentedMethod.getDeclaringType().getTypeName();
            String simpleClassName = className.substring(className.lastIndexOf('$') + 1);
            simpleClassName = simpleClassName.substring(simpleClassName.lastIndexOf('.') + 1);
            final String signature = String.format("%s#%s", simpleClassName, instrumentedMethod.getName());
            return Target.ForStackManipulation.of(signature);
        }
    };
}
 
Example #3
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 6 votes vote down vote up
private static void testStaticClassInitForDefineClass() throws Exception {
  Transformer[] transformers = new Transformer[]{
      new ConstantTransformer(DefiningClassLoader.class),
      new InvokerTransformer("getConstructor", new Class[]{Class[].class},
          new Object[]{new Class[0]}),
      new InvokerTransformer("newInstance", new Class[]{Object[].class},
          new Object[]{new Object[0]}),
      new InvokerTransformer("defineClass", new Class[]{String.class, byte[].class},
          new Object[]{"com.threedr3am.bug.collections.v3.no2.CallbackRuntime2",
              FileToByteArrayUtil.readCallbackRuntimeClassBytes(
                  "com/threedr3am/bug/collections/v3/no2/CallbackRuntime2.class")}),
      new InvokerTransformer("newInstance", new Class[]{}, new Object[]{})
  };
  Transformer transformer = new ChainedTransformer(transformers);
  Map inner = new HashMap();
  inner.put("value", "value");
  Map ouputMap = TransformedMap.decorate(inner, null, transformer);
  Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler")
      .getDeclaredConstructor(Class.class, Map.class);
  ctor.setAccessible(true);
  Object o = ctor.newInstance(Target.class, ouputMap);
  //序列化输出
  byte[] bytes = SerializeUtil.serialize(o);
  //反序列化
  SerializeUtil.deserialize(bytes);
}
 
Example #4
Source File: AnnotatedClass.java    From classpy with MIT License 6 votes vote down vote up
public void testParameterAnnotations(
    @MyRuntimeAnnotation(
        intValue = 456,
        strValue = "test",
        enumValue = ElementType.METHOD,
        classValue = String.class,
        annotationValue = @Target({ElementType.METHOD}),
        arrayValue = {"X", "Y", "Z"}
    )
    @MyClassAnnotation(
        intValue = 456,
        strValue = "test",
        enumValue = ElementType.METHOD,
        classValue = String.class,
        annotationValue = @Target({}),
        arrayValue = {"X", "Y", "Z"}
    )   
    int param1
) {
    // ...
}
 
Example #5
Source File: AnnotatedClass.java    From classpy with MIT License 6 votes vote down vote up
@MyRuntimeAnnotation(
    intValue = 456,
    strValue = "test",
    enumValue = ElementType.METHOD,
    classValue = String.class,
    annotationValue = @Target({ElementType.METHOD}),
    arrayValue = {"X", "Y", "Z"}
)
@MyClassAnnotation(
    intValue = 456,
    strValue = "test",
    enumValue = ElementType.METHOD,
    classValue = String.class,
    annotationValue = @Target({}),
    arrayValue = {"X", "Y", "Z"}
)
public void testMethodAnnotations() {
    
}
 
Example #6
Source File: TransactionalServiceAnnotationReflectionBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
private static Set<Annotation> getAllMetaAnnotations(Annotation annotation) {

        Annotation[] metaAnnotations = annotation.annotationType().getAnnotations();

        if (ObjectUtils.isEmpty(metaAnnotations)) { // 没有找到,返回空集合
            return Collections.emptySet();
        }
        // 获取所有非 Java 标准元注解结合
        Set<Annotation> metaAnnotationsSet = Stream.of(metaAnnotations)
                // 排除 Java 标准注解,如 @Target,@Documented 等,它们因相互依赖,将导致递归不断
                // 通过 java.lang.annotation 包名排除
                .filter(metaAnnotation -> !Target.class.getPackage().equals(metaAnnotation.annotationType().getPackage()))
                .collect(Collectors.toSet());

        // 递归查找元注解的元注解集合
        Set<Annotation> metaMetaAnnotationsSet = metaAnnotationsSet.stream()
                .map(TransactionalServiceAnnotationReflectionBootstrap::getAllMetaAnnotations)
                .collect(HashSet::new, Set::addAll, Set::addAll);

        // 添加递归结果
        metaMetaAnnotationsSet.add(annotation);
        return metaMetaAnnotationsSet;
    }
 
Example #7
Source File: XAnnotationUtil.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public Set<ElementType> getAnnotationTargets(JvmAnnotationType annotation) {
	EList<JvmAnnotationReference> annotations = annotation.getAnnotations();
	for (JvmAnnotationReference annoRef : annotations) {
		if (Target.class.getName().equals(annoRef.getAnnotation().getIdentifier())) {
			EList<JvmAnnotationValue> values = annoRef.getValues();
			JvmAnnotationValue value = values.isEmpty() ? null : values.get(0);
			if (value instanceof JvmEnumAnnotationValue) {
				Set<ElementType> result = newHashSet();
				for (JvmEnumerationLiteral elementType : ((JvmEnumAnnotationValue) value).getValues()) {
					final String simpleName = elementType.getSimpleName();
					result.add(ElementType.valueOf(simpleName));
				}
				return result;
			}
		}
	}
	return emptySet();
}
 
Example #8
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns true if the {@code annotationDoc} is to be treated
 * as a declaration annotation, when targeting the
 * {@code elemType} element type.
 *
 * @param annotationDoc the annotationDoc to check
 * @param elemType  the targeted elemType
 * @return true if annotationDoc is a declaration annotation
 */
public boolean isDeclarationAnnotation(AnnotationTypeDoc annotationDoc,
        boolean isJava5DeclarationLocation) {
    if (!isJava5DeclarationLocation)
        return false;
    AnnotationDesc[] annotationDescList = annotationDoc.annotations();
    // Annotations with no target are treated as declaration as well
    if (annotationDescList.length==0)
        return true;
    for (AnnotationDesc anno : annotationDescList) {
        if (anno.annotationType().qualifiedName().equals(
                Target.class.getName())) {
            if (isDeclarationTarget(anno))
                return true;
        }
    }
    return false;
}
 
Example #9
Source File: AnnotatedClassResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private AnnotationCollector _addFromBundleIfNotPresent(AnnotationCollector c,
        Annotation bundle)
{
    for (Annotation ann : ClassUtil.findClassAnnotations(bundle.annotationType())) {
        // minor optimization: by-pass 2 common JDK meta-annotations
        if ((ann instanceof Target) || (ann instanceof Retention)) {
            continue;
        }
        if (!c.isPresent(ann)) {
            c = c.addOrOverride(ann);
            if (_intr.isAnnotationBundle(ann)) {
                c = _addFromBundleIfNotPresent(c, ann);
            }
        }
    }
    return c;
}
 
Example #10
Source File: TestFixture.java    From jfixture with 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 #11
Source File: TypeAnnotationRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IAnnotationBinding findTargetAnnotation(IAnnotationBinding[] metaAnnotations) {
	for (int i= 0; i < metaAnnotations.length; i++) {
		IAnnotationBinding binding= metaAnnotations[i];
		ITypeBinding annotationType= binding.getAnnotationType();
		if (annotationType != null && annotationType.getQualifiedName().equals(Target.class.getName())) {
			return binding;
		}
	}
	return null;
}
 
Example #12
Source File: SqliteMagicImplicitUsageProvider.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
public SqliteMagicImplicitUsageProvider() {
  for (Class<? extends Annotation> annotation : ANNOTATIONS) {
    final EnumSet<ElementType> elementTypes = EnumSet.copyOf(Arrays.asList(annotation.getAnnotation(Target.class).value()));
    if (elementTypes.contains(ElementType.FIELD)) {
      FIELD_ANNOTATIONS.add(annotation.getName());
    }
    if (elementTypes.contains(ElementType.METHOD) || elementTypes.contains(ElementType.CONSTRUCTOR)) {
      METHOD_ANNOTATIONS.add(annotation.getName());
    }
    if (elementTypes.contains(ElementType.TYPE)) {
      CLASS_ANNOTATIONS.add(annotation.getName());
    }
  }
}
 
Example #13
Source File: RDFProperty.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private void annotationHeader(JavaMessageBuilder builder)
		throws ObjectStoreConfigException {
	String pkg = builder.getPackageName(this.getURI());
	String simple = builder.getSimpleName(this.getURI());
	if (pkg == null) {
		builder.imports(simple);
	} else {
		builder.pkg(pkg);
		builder.imports(pkg + '.' + simple);
	}
	builder.comment(this);
	if (this.isA(OWL.DEPRECATEDPROPERTY)) {
		builder.annotate(Deprecated.class);
	}
	builder.annotateEnum(Retention.class, "value", RetentionPolicy.class, "RUNTIME");
	builder.annotateEnums(Target.class, "value", ElementType.class, "TYPE", "METHOD",
				"PARAMETER", "ANNOTATION_TYPE", "PACKAGE");
	builder.annotationName(simple);
	builder.annotationProperties(this);
	builder.annotateURI(Iri.class, "value", builder.getType(this.getURI()));
	if (this.isA(OWL.FUNCTIONALPROPERTY)) {
		builder.method("value", true).returnType(builder.imports(String.class)).end();
	} else {
		builder.method("value", true).returnType(builder.imports(String.class) + "[]")
				.end();
	}
}
 
Example #14
Source File: IndexFileWriter.java    From annotation-tools with MIT License 5 votes vote down vote up
private Collection<Annotation> requiredMetaannotations(
        Collection<Annotation> annos) {
    Set<Annotation> results = new HashSet<>();
    for (Annotation a : annos) {
        String aName = a.def.name;
        if (aName.equals(Retention.class.getCanonicalName())
            || aName.equals(Target.class.getCanonicalName())) {
            results.add(a);
        }
    }
    return results;
}
 
Example #15
Source File: TestFromListOf.java    From jfixture with MIT License 5 votes vote down vote up
@Test
public void Annotation_can_only_be_applied_to_fields() {
    Target target = FromListOf.class.getAnnotation(Target.class);
    assertEquals(1, target.value().length);
    ElementType type = target.value()[0];
    assertEquals(ElementType.FIELD, type);
}
 
Example #16
Source File: TestRange.java    From jfixture with MIT License 5 votes vote down vote up
@Test
public void Annotation_can_only_be_applied_to_fields() {
    Target target = Range.class.getAnnotation(Target.class);
    assertEquals(1, target.value().length);
    ElementType type = target.value()[0];
    assertEquals(ElementType.FIELD, type);
}
 
Example #17
Source File: AnnotationUtils.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public static <A extends Annotation> AnnotatedElement getAnnotatedElement(Class<?> clazz, Class<A> annotationType) {
	if (clazz == null || annotationType == null) {
		return null;
	}
	Target target = annotationType.getAnnotation(Target.class);
	if (target == null) {
		return null;
	}
	AnnotatedElement element = null;
	ElementType[] value = target.value();
	for (ElementType elementType : value) {

		switch (elementType) {
		case FIELD:
			element = getField(clazz, annotationType);
			break;
		case METHOD:
			element = getMethod(clazz, annotationType);
			break;
		case TYPE:
			element = getType(clazz, annotationType);
			break;
		default:
			break;
		}
		if (element != null) {
			break;
		}
	}
	return element;
}
 
Example #18
Source File: MetaAnnotationHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private static boolean validTarget(Class<? extends Annotation> type) {
	final Target target = type.getAnnotation(Target.class);

	if(target==null) {
		return false;
	}

	final ElementType[] targets=target.value();

	return 
		targets.length == 1 && 
		targets[0] == ElementType.ANNOTATION_TYPE;
}
 
Example #19
Source File: JAXBUtils.java    From cxf with 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 #20
Source File: PropertyAnnotationsTest.java    From auto with 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 #21
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 #22
Source File: AnnotationValueOffsetMappingFactory.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public Advice.OffsetMapping make(final ParameterDescription.InDefinedShape target,
                                 final AnnotationDescription.Loadable<AnnotationValueExtractor> annotation,
                                 final AdviceType adviceType) {
    return new Advice.OffsetMapping() {
        @Override
        public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {
            return Target.ForStackManipulation.of(getAnnotationValue(instrumentedMethod, annotation.load()));
        }
    };
}
 
Example #23
Source File: JaxRsOffsetMappingFactory.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<JaxRsPath> annotation, AdviceType adviceType) {
    return new Advice.OffsetMapping() {
        @Override
        public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {
            Object value = null;
            if (useAnnotationValueForTransactionName) {
                value = getTransactionAnnotationValueFromAnnotations(instrumentedMethod, instrumentedType);
            }
            return Target.ForStackManipulation.of(value);
        }
    };
}
 
Example #24
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 5 votes vote down vote up
private static void testAnnotationInvocationHandlerForDefineClass() throws Exception {
  Transformer[] transformers = new Transformer[]{
      new ConstantTransformer(DefiningClassLoader.class),
      new InvokerTransformer("getConstructor", new Class[]{Class[].class},
          new Object[]{new Class[0]}),
      new InvokerTransformer("newInstance", new Class[]{Object[].class},
          new Object[]{new Object[0]}),
      new InvokerTransformer("defineClass", new Class[]{String.class, byte[].class},
          new Object[]{"com.threedr3am.bug.collections.v3.no2.CallbackRuntime",
              FileToByteArrayUtil.readCallbackRuntimeClassBytes(
                  "com/threedr3am/bug/collections/v3/no2/CallbackRuntime.class")}),
      new InvokerTransformer("newInstance", new Class[]{}, new Object[]{}),
      new InvokerTransformer("exec", new Class[]{String.class},
          new Object[]{"/Applications/Calculator.app/Contents/MacOS/Calculator"})
  };
  Transformer transformer = new ChainedTransformer(transformers);
  Map inner = new HashMap();
  inner.put("value", "value");
  Map ouputMap = TransformedMap.decorate(inner, null, transformer);
  Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler")
      .getDeclaredConstructor(Class.class, Map.class);
  ctor.setAccessible(true);
  Object o = ctor.newInstance(Target.class, ouputMap);
  //序列化输出
  byte[] bytes = SerializeUtil.serialize(o);
  //反序列化
  SerializeUtil.deserialize(bytes);
}
 
Example #25
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 5 votes vote down vote up
/**
 * 测试AnnotationInvocationHandler反序列化中,直接触发Transformer
 *
 */
private static void testAnnotationInvocationHandlerMap(Transformer transformer) throws Exception{
    //转化map
    Map innerMap = new HashMap();
    innerMap.put("value","2");
    Map ouputMap = TransformedMap.decorate(innerMap,null,transformer);
    //jdk1.8该类的方法readObject()是使用了native方法安全更新map,无法再触发
    Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler").getDeclaredConstructor(Class.class,Map.class);
    ctor.setAccessible(true);
    InvocationHandler o = (InvocationHandler) ctor.newInstance(Target.class,ouputMap);
    //序列化输出
    byte[] bytes = SerializeUtil.serialize(o);
    //反序列化
    SerializeUtil.deserialize(bytes);
}
 
Example #26
Source File: TargetAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean hasTarget() {
    Map<String, ? extends AnnotationMirror> types = getHelper()
            .getAnnotationsByType(getElement().getAnnotationMirrors());
    AnnotationMirror target = types.get(Target.class.getCanonicalName());
    if (target == null) {
        handleNoTarget();
    }
    return hasReqiredTarget( target , getDeclaredTargetTypes( getHelper(), 
            target ));
}
 
Example #27
Source File: TargetAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Set<ElementType> getDeclaredTargetTypes() {
    Map<String, ? extends AnnotationMirror> types = getHelper()
            .getAnnotationsByType(getElement().getAnnotationMirrors());
    AnnotationMirror target = types.get(Target.class.getCanonicalName());
    if (target == null) {
        return Collections.emptySet();
    }
    return getDeclaredTargetTypes( getHelper(), target );
}
 
Example #28
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 #29
Source File: ExtraLongTest.java    From OnActivityResult with Apache License 2.0 4 votes vote down vote up
@Test
public void testAnnotationTarget() {
    final Target retention = ExtraLong.class.getAnnotation(Target.class);
    final ElementType[] elementTypes = retention.value();
    assertArrayEquals(new ElementType[] { ElementType.PARAMETER }, elementTypes);
}
 
Example #30
Source File: NonFieldTargetDetector.java    From aircon with MIT License 4 votes vote down vote up
private boolean isTargetAnnotation(final UAnnotation annotation) {
	return ElementUtils.isOfType(annotation.getJavaPsi(), Target.class);
}