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; }
private JDefinedClass buildTemplateConstraint(String name) { try { JDefinedClass tplConstraint = codeModel._class(Config.CFG.getBasePackageName() + ".annot."+name, ClassType.ANNOTATION_TYPE_DECL); tplConstraint.annotate(Documented.class); tplConstraint.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME); tplConstraint.annotate(Target.class).paramArray("value").param(ElementType.TYPE).param(ElementType.ANNOTATION_TYPE).param(ElementType.FIELD).param(ElementType.METHOD); // Using direct as I don't know how to build default { } with code model tplConstraint.direct("\n" + " Class<?>[] groups() default {};\n" + " String message() default \"Invalid value\";\n" + " Class<? extends Payload>[] payload() default {};\n"); // Hack to force the import of javax.validation.Payload tplConstraint.javadoc().addThrows((JClass) codeModel._ref(Payload.class)).add("Force import"); return tplConstraint; } catch (JClassAlreadyExistsException e) { throw new RuntimeException("Tried to create an already existing class: " + name, e); } }
/** * 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; }
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(); }
@Test void rootAnnotation() { CompilationUnit unit = CompilationUnit.of("test"); Annotation annotation = Annotation.of(All.class); annotation.addObject("o", Annotation.of(Target.class, ElementType.TYPE)); annotation.addObject("p", 4711); annotation.addObject("r", Double.class); annotation.addObject("r", Float.class); NormalClassDeclaration type = unit.declareClass("Root"); type.addAnnotation(annotation); type.addTypeParameter(TypeParameter.of("X")); mark(type.declareField(TypeVariable.of("X"), "i")); Counter counter = new Counter(); Compilation.compile(null, emptyList(), asList(counter), asList(unit.toJavaFileObject())); assertEquals(1, counter.annotations.size()); assertEquals(annotation.list(), counter.annotations.get(0).list()); }
@Test public void loadAndCheckAnnotatedAnnotation() throws Exception { ClassInfo classInfo = ClassInfo.newAnnotation() .name("org.kordamp.naum.processor.klass.AnnotatedAnnotation") .iface(Annotation.class.getName()) .build(); classInfo.addToAnnotations(annotationInfo() .name(Retention.class.getName()) .annotationValue("value", new EnumValue(RetentionPolicy.class.getName(), "SOURCE")) .build()); classInfo.addToAnnotations(annotationInfo() .name(Target.class.getName()) .annotationValue("value", newArrayValue(asList( newEnumValue(ElementType.class.getName(), ElementType.TYPE.name()), newEnumValue(ElementType.class.getName(), ElementType.FIELD.name())) )) .build()); loadAndCheck("org/kordamp/naum/processor/klass/AnnotatedAnnotation.class", (klass) -> { assertThat(klass.getContentHash(), equalTo(classInfo.getContentHash())); assertThat(klass, equalTo(classInfo)); }); }
private static void annotationTypeAnnotation() { // @Target这个就是 此类型 ClassBinds classBinds = Test.class.getAnnotation(ClassBinds.class); if (classBinds != null) { Annotation[] annotations = classBinds.annotationType().getAnnotations(); Target target = classBinds.annotationType().getAnnotation(Target.class); if (target != null) System.out.print("ANNOTATION_TYPE---->targets:" ); for (ElementType elementType : target.value()) { System.out.print("\t elementType:"+elementType); } System.out.println(); } }
private void getAllReflectionClasses() throws NotFoundException{ //System annotations addClassIfNotExists(typeOracle.getType(Retention.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle)); addClassIfNotExists(typeOracle.getType(Documented.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle)); addClassIfNotExists(typeOracle.getType(Inherited.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle)); addClassIfNotExists(typeOracle.getType(Target.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle)); addClassIfNotExists(typeOracle.getType(Deprecated.class.getCanonicalName()), ReflectableHelper.getDefaultSettings(typeOracle)); //typeOracle.getType("org.lirazs.gbackbone.client.test.reflection.TestReflectionGenerics.TestReflection1"); //=====GWT0.7 for (JClassType classType : typeOracle.getTypes()) { Reflectable reflectable = GenUtils.getClassTypeAnnotationWithMataAnnotation(classType, Reflectable.class); if (reflectable != null){ processClass(classType, reflectable); if (reflectable.assignableClasses()){ for (JClassType type : classType.getSubtypes()){ processClass(type, reflectable); } } } } //======end of gwt0.7 }
/** * 获得 method. * * @param joinPoint * the join point * @param klass * the klass * @return the method * @deprecated 目前作用不大,将来会重构 */ @Deprecated protected Method getMethod(JoinPoint joinPoint,Class<? extends Annotation> klass){ MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(klass)){ return method; } Target annotation = klass.getAnnotation(Target.class); ElementType[] value = annotation.value(); try{ Object target = joinPoint.getTarget(); Class<? extends Object> targetClass = target.getClass(); String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); Method m1 = targetClass.getMethod(methodName, parameterTypes); if (m1.isAnnotationPresent(klass)){ return m1; } }catch (Exception e){ LOGGER.error(e.getClass().getName(), e); } throw new RuntimeException("No Proper annotation found."); }
/** * Checks if is annotation present. * * @param joinPoint * the join point * @param klass * the klass * @return true, if checks if is annotation present * @deprecated 目前作用不大,将来会重构 */ @Deprecated protected boolean isAnnotationPresent(JoinPoint joinPoint,Class<? extends Annotation> klass){ MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(klass)){ return true; } Target annotation = klass.getAnnotation(Target.class); ElementType[] value = annotation.value(); try{ Object target = joinPoint.getTarget(); Class<? extends Object> targetClass = target.getClass(); String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); Method m1 = targetClass.getMethod(methodName, parameterTypes); if (m1.isAnnotationPresent(klass)){ return true; } }catch (Exception e){ LOGGER.error(e.getClass().getName(), e); } return false; }
@Nullable private static Class<Annotation> getDeclaredAnnotationClass(AnnotationMirror mirror) throws ClassNotFoundException { TypeElement element = (TypeElement) mirror.getAnnotationType().asElement(); // Ensure the annotation has the correct retention and targets. Retention retention = element.getAnnotation(Retention.class); if (retention != null && retention.value() != RetentionPolicy.RUNTIME) { return null; } Target target = element.getAnnotation(Target.class); if (target != null) { if (target.value().length < 2) { return null; } List<ElementType> targets = Arrays.asList(target.value()); if (!(targets.contains(ElementType.TYPE) && targets.contains(ElementType.ANNOTATION_TYPE))) { return null; } } return (Class<Annotation>) Class.forName(element.getQualifiedName().toString()); }
@Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (ANNOTATION_WITH_SCOPE_AND_TARGET.matches(classTree, state)) { MultiMatchResult<AnnotationTree> targetAnnotation = HAS_TARGET_ANNOTATION.multiMatchResult(classTree, state); if (targetAnnotation.matches()) { AnnotationTree targetTree = targetAnnotation.onlyMatchingNode(); Target target = getAnnotation(classTree, Target.class); if (target != null && // Unlikely to occur, but just in case Target isn't on the classpath. !Arrays.asList(target.value()).containsAll(REQUIRED_ELEMENT_TYPES)) { return describeMatch(targetTree, replaceTargetAnnotation(target, targetTree)); } } } return Description.NO_MATCH; }
@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() { }
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 ) { // ... }
/** * */ public void test_isAnnotationPresent_Cla() { class e {}; assertFalse("zzz annotation is not presented for e class!", e.class.isAnnotationPresent(zzz.class)); assertFalse("zzz annotation is not presented for zzz class!", zzz.class.isAnnotationPresent(zzz.class)); assertTrue("Target annotation is presented for zzz class!", zzz.class.isAnnotationPresent(java.lang.annotation .Target.class)); assertTrue("Documented annotation is presented for zzz class!", zzz.class.isAnnotationPresent(java.lang.annotation .Documented.class)); assertTrue("Retention annotation is presented for zzz class!", zzz.class.isAnnotationPresent(java.lang.annotation .Retention.class)); }
/** * */ public void test_getAnnotation_Cla() { class e {}; assertNull("zzz annotation is not presented in e class!", e.class.getAnnotation(zzz.class)); assertNull("zzz annotation is not presented in zzz class!", zzz.class.getAnnotation(zzz.class)); assertFalse("Target annotation is presented in zzz class!", zzz.class.getAnnotation(java.lang.annotation.Target.class) .toString().indexOf("java.lang.annotation.Target") == -1); assertFalse("Documented annotation is presented in zzz class!", zzz.class.getAnnotation(java.lang.annotation.Documented.class) .toString().indexOf("java.lang.annotation.Documented") == -1); assertFalse("Retention annotation is presented in zzz class!", zzz.class.getAnnotation(java.lang.annotation.Retention.class) .toString().indexOf("java.lang.annotation.Retention") == -1); }
@Test public void testGetAnnotationFieldsWithSimpelClass() { List<Field> fields = ReflectionUtils.getAnnotationFields(SimpleClass.class, TestAnnotation.class); Assert.assertEquals("SimpleClass does not contain any field annotated with TestAnnotation", 0, fields.size()); fields = ReflectionUtils.getAnnotationFields(SimpleClassWithAnnotation.class, TestAnnotation.class); Assert.assertEquals("SimpleClassWithAnnotation contains a field annotated with TestAnnotation", 1, fields.size()); fields = ReflectionUtils.getAnnotationFields(SubClass.class, TestAnnotation.class); Assert.assertEquals("SubClass contains a superclass field annotated with TestAnnotation", 1, fields.size()); fields = ReflectionUtils.getAnnotationFields(SubSubClass.class, TestAnnotation.class); Assert.assertEquals("SubClass contains a field and a superclass field annotated with TestAnnotation", 2, fields.size()); fields = ReflectionUtils.getAnnotationFields(SubSubClass.class, Target.class); Assert.assertEquals("SubClass contains no fields annotated with Target", 0, fields.size()); }
@Override @SuppressWarnings("unchecked") public final Description matchClass(ClassTree classTree, VisitorState state) { Symbol classSymbol = ASTHelpers.getSymbol(classTree); if ((classSymbol.flags() & Flags.ANNOTATION) != 0 && SCOPE_ANNOTATION_MATCHER.matches(classTree, state)) { Target target = ASTHelpers.getAnnotation(classSymbol, Target.class); boolean hasExclusivelyTypeAndOrMethodTargeting = false; if (target != null) { for (ElementType elementType : target.value()) { if (elementType != METHOD && elementType != TYPE) { return describe(classTree, state); } else if (elementType == METHOD || elementType == TYPE) { hasExclusivelyTypeAndOrMethodTargeting = true; } } } if(!hasExclusivelyTypeAndOrMethodTargeting) { // true for no target set and for @Target({}) return describe(classTree, state); } } return Description.NO_MATCH; }
@Before public void setUp() { mappers = new HashMap<>(); mappers.put(Retention.class, mapper1); mappers.put(Target.class, mapper2); converters = new HashMap<>(); converters.put(Retention.class, converter1); converters.put(Target.class, converter2); config = new QueriesConfigImpl(dialect, binder, mappers, converters); }
@Test public void shouldBeEqualToRealAnnotationWithArrayValues() throws Exception { Map<String, Object> values = new HashMap<>(); values.put("value", new ElementType[] {ElementType.TYPE, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.METHOD}); Target target = AnnotationFactory.create(Target.class, values); Target real = TestAnnotation.class.getAnnotation(Target.class); assertThat(target).isInstanceOf(Target.class); assertThat(target).isEqualTo(real); assertThat(target.hashCode()).isEqualTo(real.hashCode()); }
private JDefinedClass createCustomHttpMethodAnnotation(final String httpMethod) throws JClassAlreadyExistsException { final JPackage pkg = codeModel._package(getSupportPackage()); final JDefinedClass annotationClazz = pkg._annotationTypeDeclaration(httpMethod); annotationClazz.annotate(Target.class).param("value", ElementType.METHOD); annotationClazz.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME); annotationClazz.annotate(HttpMethod.class).param("value", httpMethod); annotationClazz.javadoc().add("Custom JAX-RS support for HTTP " + httpMethod + "."); httpMethodAnnotations.put(httpMethod.toUpperCase(), annotationClazz); return annotationClazz; }
@Test void singleElementAnnotationUsingEnumValues() { Annotation target = Annotation.of(Target.class, ElementType.TYPE); String t = Target.class.getCanonicalName(); String et = ElementType.class.getCanonicalName(); assertEquals("@" + t + "(" + et + ".TYPE)", target.list()); target.addObject("value", ElementType.PACKAGE); assertEquals("@" + t + "({" + et + ".TYPE, " + et + ".PACKAGE})", target.list()); }
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; }
/** * Execute one hook if is present. * * @param ann the annotation * @param execute the bi consumer * @param <T> the type */ protected <T> void doHookIfPresent(Class<T> ann, BiConsumer<AnnotatedElement, T> execute) { Class<? extends Annotation> annClass = (Class<? extends Annotation>) ann; Target target = annClass.getAnnotation(Target.class); if (isCheckType(target, ElementType.TYPE)) executeHookType(annClass, execute); if (isCheckType(target, ElementType.METHOD)) executeHookMethods(annClass, execute); }
/** * Execute one hook if is present. * * @param ann the annotation * @param execute the handler * @param <T> the type */ protected <T> void doHookIfPresent(Class<T> ann, Handler<T> execute) { Class<? extends Annotation> annClass = (Class<? extends Annotation>) ann; Target target = annClass.getAnnotation(Target.class); if (isCheckType(target, ElementType.TYPE)) { executeHookType(annClass, (a, t) -> execute.handle((T) t)); } if (isCheckType(target, ElementType.METHOD)) { executeHookMethods(annClass, (a, t) -> execute.handle((T) t)); } }
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()); } } }
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(); } }
private AnnotationNode getTargetAnnotation(final String resolvedTarget) { final List<ElementType> types = resolveAnnotationTarget(resolvedTarget); final ListExpression listExpr = resolveTargetFromElementType(types); return A.NODES.annotation(Target.class) .member(A.UTIL.ANNOTATION.ANNOTATION_VALUE, listExpr) .build(); }
private Collection<Annotation> requiredMetaannotations( Collection<Annotation> annos) { Set<Annotation> results = new HashSet<Annotation>(); 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; }
/** * Returns a set of meta annotations associated with the given annotation * bundle. This will suppress {@link java.lang.annotation.Retention} and * {@link java.lang.annotation.Target}. The supplied annotation will be * the first annotation included in the returned set. */ public static Set<Annotation> getMetaAnnotations(Annotation bundle) { Set<Annotation> result = Sets.newLinkedHashSet(); result.add(Objects.notNull(bundle)); for (Annotation a : bundle.annotationType().getDeclaredAnnotations()) { // minor optimization: by-pass 2 common JDK meta-annotations if ((a instanceof Target) || (a instanceof Retention)) { continue; } result.add(a); } return result; }
public void test_computeDependencies_fromAno_public() { for (boolean apiOnly : FALSE_TRUE) { final SortedSet<String> expected = new TreeSet<String>(); // // Extends Object. addSlashedName(expected, Object.class); // Implements Annotation. addSlashedName(expected, Annotation.class); // addSlashedName(expected, Class.class); addSlashedName(expected, Number.class); addSlashedName(expected, Byte.class); addSlashedName(expected, String.class); addSlashedName(expected, RoundingMode.class); addSlashedName(expected, Documented.class); // if (apiOnly) { } else { addSlashedName(expected, Retention.class); addSlashedName(expected, RetentionPolicy.class); addSlashedName(expected, Target.class); addSlashedName(expected, ElementType.class); // addSlashedName(expected, ClassDepsParserTest.class); } computeDepsAndCheck(MyTestAnno2_public.class.getName(), apiOnly, expected); } }
public void test_computeDependencies_fromAno_private() { for (boolean apiOnly : FALSE_TRUE) { final SortedSet<String> expected = new TreeSet<String>(); // if (apiOnly) { } else { addSlashedName(expected, Retention.class); addSlashedName(expected, RetentionPolicy.class); addSlashedName(expected, Target.class); addSlashedName(expected, ElementType.class); // addSlashedName(expected, ClassDepsParserTest.class); // addSlashedName(expected, Object.class); addSlashedName(expected, Annotation.class); // addSlashedName(expected, Class.class); addSlashedName(expected, Number.class); addSlashedName(expected, Byte.class); addSlashedName(expected, String.class); addSlashedName(expected, RoundingMode.class); addSlashedName(expected, Documented.class); } computeDepsAndCheck(MyTestAnno2_private.class.getName(), apiOnly, expected); } }
private boolean _isValidElement(Element pElement) { Retention retention = pElement.getAnnotation(Retention.class); if (retention == null || retention.value() != RetentionPolicy.RUNTIME) { processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING, "Retention should be RUNTIME", pElement); return false; } Target target = pElement.getAnnotation(Target.class); if (target == null || target.value() == null || target.value().length == 0) { processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING, "Target has to be defined", pElement); return false; } else { for (ElementType elementType : target.value()) { if (elementType != ElementType.TYPE) { processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING, "Unsupported type: " + elementType, pElement); return false; } } } return true; }
@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]; assertTrue(type.equals(ElementType.FIELD)); }
@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]; assertTrue(type.equals(ElementType.FIELD)); }
@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]; assertTrue(type.equals(ElementType.FIELD)); }