java.lang.reflect.AnnotatedElement Java Examples
The following examples show how to use
java.lang.reflect.AnnotatedElement.
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: ClassMemberScaner.java From mPaaS with Apache License 2.0 | 6 votes |
/** 递归扫描字段 */ private boolean scanField(Class<?> clazz, List<String> visited, Consumer<AnnotatedElement> consumer) { // 扫描当前类 for (Field field : clazz.getDeclaredFields()) { String name = field.getName(); if (!visited.contains(name)) { if (handle(field, consumer)) { return true; } visited.add(name); } } // 扫描父类 Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && superClazz != Object.class) { if (scanField(superClazz, visited, consumer)) { return true; } } return false; }
Example #2
Source File: SpringCacheAnnotationParser.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Validates the specified {@link CacheOperation}. * <p>Throws an {@link IllegalStateException} if the state of the operation is * invalid. As there might be multiple sources for default values, this ensure * that the operation is in a proper state before being returned. * @param ae the annotated element of the cache operation * @param operation the {@link CacheOperation} to validate */ private void validateCacheOperation(AnnotatedElement ae, CacheOperation operation) { if (StringUtils.hasText(operation.getKey()) && StringUtils.hasText(operation.getKeyGenerator())) { throw new IllegalStateException("Invalid cache annotation configuration on '" + ae.toString() + "'. Both 'key' and 'keyGenerator' attributes have been set. " + "These attributes are mutually exclusive: either set the SpEL expression used to" + "compute the key at runtime or set the name of the KeyGenerator bean to use."); } if (StringUtils.hasText(operation.getCacheManager()) && StringUtils.hasText(operation.getCacheResolver())) { throw new IllegalStateException("Invalid cache annotation configuration on '" + ae.toString() + "'. Both 'cacheManager' and 'cacheResolver' attributes have been set. " + "These attributes are mutually exclusive: the cache manager is used to configure a" + "default cache resolver if none is set. If a cache resolver is set, the cache manager" + "won't be used."); } }
Example #3
Source File: ProviderSkeleton.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
/** * Utility method for calling an arbitrary method in an annotation. * * @param element the element that was annotated, either a class or method * @param annotation the class of the annotation we're interested in * @param methodName the name of the method in the annotation we wish * to call. * @param defaultValue the value to return if the annotation doesn't * exist, or we couldn't invoke the method for some reason. * @return the result of calling the annotation method, or the default. */ protected static Object getAnnotationValue( AnnotatedElement element, Class<? extends Annotation> annotation, String methodName, Object defaultValue) { Object ret = defaultValue; try { Method m = annotation.getMethod(methodName); Annotation a = element.getAnnotation(annotation); ret = m.invoke(a); } catch (NoSuchMethodException e) { assert false; } catch (IllegalAccessException e) { assert false; } catch (InvocationTargetException e) { assert false; } catch (NullPointerException e) { assert false; } return ret; }
Example #4
Source File: CommonAnnotationBeanPostProcessor.java From spring4-understanding with Apache License 2.0 | 6 votes |
public EjbRefElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) { super(member, pd); EJB resource = ae.getAnnotation(EJB.class); String resourceBeanName = resource.beanName(); String resourceName = resource.name(); this.isDefaultName = !StringUtils.hasLength(resourceName); if (this.isDefaultName) { resourceName = this.member.getName(); if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) { resourceName = Introspector.decapitalize(resourceName.substring(3)); } } Class<?> resourceType = resource.beanInterface(); if (resourceType != null && Object.class != resourceType) { checkResourceType(resourceType); } else { // No resource type specified... check field/method. resourceType = getResourceType(); } this.beanName = resourceBeanName; this.name = resourceName; this.lookupType = resourceType; this.mappedName = resource.mappedName(); }
Example #5
Source File: AnnotationUtils.java From spring-analysis-note with MIT License | 6 votes |
/** * Handle the supplied annotation introspection exception. * <p>If the supplied exception is an {@link AnnotationConfigurationException}, * it will simply be thrown, allowing it to propagate to the caller, and * nothing will be logged. * <p>Otherwise, this method logs an introspection failure (in particular * {@code TypeNotPresentExceptions}) before moving on, assuming nested * Class values were not resolvable within annotation attributes and * thereby effectively pretending there were no annotations on the specified * element. * @param element the element that we tried to introspect annotations on * @param ex the exception that we encountered * @see #rethrowAnnotationConfigurationException */ private static void handleIntrospectionFailure(@Nullable AnnotatedElement element, Throwable ex) { rethrowAnnotationConfigurationException(ex); IntrospectionFailureLogger logger = IntrospectionFailureLogger.INFO; boolean meta = false; if (element instanceof Class && Annotation.class.isAssignableFrom((Class<?>) element)) { // Meta-annotation or (default) value lookup on an annotation type logger = IntrospectionFailureLogger.DEBUG; meta = true; } if (logger.isEnabled()) { String message = meta ? "Failed to meta-introspect annotation " : "Failed to introspect annotations on "; logger.log(message + element + ": " + ex); } }
Example #6
Source File: DefaultElementByBuilder.java From java-client with Apache License 2.0 | 6 votes |
@Override protected By buildMobileNativeBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); HowToUseLocators howToUseLocators = annotatedElement.getAnnotation(HowToUseLocators.class); Optional<HowToUseLocators> howToUseLocatorsOptional = ofNullable(howToUseLocators); if (isAndroid()) { return buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::androidAutomation).orElse(null), getBys(AndroidFindBy.class, AndroidFindBys.class, AndroidFindAll.class)); } if (isIOSXcuit() || isIOS()) { return buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::iOSXCUITAutomation).orElse(null), getBys(iOSXCUITFindBy.class, iOSXCUITFindBys.class, iOSXCUITFindAll.class)); } if (isWindows()) { return buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::windowsAutomation).orElse(null), getBys(WindowsFindBy.class, WindowsFindBys.class, WindowsFindAll.class)); } return null; }
Example #7
Source File: CreoleAnnotationHandler.java From gate-core with GNU Lesser General Public License v3.0 | 6 votes |
/** * Given a single-argument method whose parameter is a {@link Collection}, use * the method's generic type information to determine the collection element * type and store it as the ITEM_CLASS_NAME attribute of the given Element. * * @param method * the setter method * @param paramElt * the PARAMETER element */ private void determineCollectionElementType(AnnotatedElement method, Type paramType, Element paramElt) { if(paramElt.getAttributeValue("ITEM_CLASS_NAME") == null) { Class<?> elementType; CreoleParameter paramAnnot = method.getAnnotation(CreoleParameter.class); if(paramAnnot != null && paramAnnot.collectionElementType() != CreoleParameter.NoElementType.class) { elementType = paramAnnot.collectionElementType(); } else { elementType = findCollectionElementType(paramType); } if(elementType != null) { paramElt.setAttribute("ITEM_CLASS_NAME", elementType.getName()); } } }
Example #8
Source File: ChangeService.java From mongobee with Apache License 2.0 | 6 votes |
private boolean matchesActiveSpringProfile(AnnotatedElement element) { if (!ClassUtils.isPresent("org.springframework.context.annotation.Profile", null)) { return true; } if (!element.isAnnotationPresent(Profile.class)) { return true; // no-profiled changeset always matches } List<String> profiles = asList(element.getAnnotation(Profile.class).value()); for (String profile : profiles) { if (profile != null && profile.length() > 0 && profile.charAt(0) == '!') { if (!activeProfiles.contains(profile.substring(1))) { return true; } } else if (activeProfiles.contains(profile)) { return true; } } return false; }
Example #9
Source File: ReflectionBasedJsr303AnnotationTrollerBase.java From backstopper with Apache License 2.0 | 6 votes |
/** * @return The list of annotation->owningElement pairs from the given 2-dimensional array that match the given * desiredAnnotationClass - note that if desiredAnnotationClassIsMultiValueConstraint is true then each matching * annotation will be exploded via {@link #explodeAnnotationToManyConstraintsIfMultiValue(java.lang.annotation.Annotation, * boolean)} before being added to the return list. */ private static List<Pair<Annotation, AnnotatedElement>> extractAnnotationsFrom2dArray( Annotation[][] annotations2dArray, Class<? extends Annotation> desiredAnnotationClass, boolean desiredAnnotationClassIsMultiValueConstraint, AnnotatedElement owningElement) { List<Pair<Annotation, AnnotatedElement>> returnList = new ArrayList<>(); for (Annotation[] innerArray : annotations2dArray) { for (Annotation annotation : innerArray) { if (annotation.annotationType().equals(desiredAnnotationClass)) { List<Annotation> annotationsToRegister = explodeAnnotationToManyConstraintsIfMultiValue( annotation, desiredAnnotationClassIsMultiValueConstraint ); for (Annotation annotationToRegister : annotationsToRegister) { returnList.add(Pair.of(annotationToRegister, owningElement)); } } } } return returnList; }
Example #10
Source File: SpringCacheAnnotationParser.java From java-technology-stack with MIT License | 6 votes |
/** * Validates the specified {@link CacheOperation}. * <p>Throws an {@link IllegalStateException} if the state of the operation is * invalid. As there might be multiple sources for default values, this ensure * that the operation is in a proper state before being returned. * @param ae the annotated element of the cache operation * @param operation the {@link CacheOperation} to validate */ private void validateCacheOperation(AnnotatedElement ae, CacheOperation operation) { if (StringUtils.hasText(operation.getKey()) && StringUtils.hasText(operation.getKeyGenerator())) { throw new IllegalStateException("Invalid cache annotation configuration on '" + ae.toString() + "'. Both 'key' and 'keyGenerator' attributes have been set. " + "These attributes are mutually exclusive: either set the SpEL expression used to" + "compute the key at runtime or set the name of the KeyGenerator bean to use."); } if (StringUtils.hasText(operation.getCacheManager()) && StringUtils.hasText(operation.getCacheResolver())) { throw new IllegalStateException("Invalid cache annotation configuration on '" + ae.toString() + "'. Both 'cacheManager' and 'cacheResolver' attributes have been set. " + "These attributes are mutually exclusive: the cache manager is used to configure a" + "default cache resolver if none is set. If a cache resolver is set, the cache manager" + "won't be used."); } }
Example #11
Source File: RunAsAdvice.java From alfresco-mvc with Apache License 2.0 | 6 votes |
private AlfrescoRunAs parseRunAsAnnotation(AnnotatedElement ae) { AlfrescoRunAs ann = ae.getAnnotation(AlfrescoRunAs.class); if (ann == null) { for (Annotation metaAnn : ae.getAnnotations()) { ann = metaAnn.annotationType().getAnnotation(AlfrescoRunAs.class); if (ann != null) { break; } } } if (ann != null) { return parseAnnotation(ann); } else { return null; } }
Example #12
Source File: AnnotationUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private void process(AnnotatedElement element) { if (this.visited.add(element)) { try { Annotation[] annotations = (this.declaredMode ? element.getDeclaredAnnotations() : element.getAnnotations()); for (Annotation ann : annotations) { Class<? extends Annotation> currentAnnotationType = ann.annotationType(); if (ObjectUtils.nullSafeEquals(this.annotationType, currentAnnotationType)) { this.result.add(synthesizeAnnotation((A) ann, element)); } else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, currentAnnotationType)) { this.result.addAll(getValue(element, ann)); } else if (!isInJavaLangAnnotationPackage(ann)) { process(currentAnnotationType); } } } catch (Exception ex) { handleIntrospectionFailure(element, ex); } } }
Example #13
Source File: AnnotationUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Handle the supplied annotation introspection exception. * <p>If the supplied exception is an {@link AnnotationConfigurationException}, * it will simply be thrown, allowing it to propagate to the caller, and * nothing will be logged. * <p>Otherwise, this method logs an introspection failure (in particular * {@code TypeNotPresentExceptions}) before moving on, assuming nested * Class values were not resolvable within annotation attributes and * thereby effectively pretending there were no annotations on the specified * element. * @param element the element that we tried to introspect annotations on * @param ex the exception that we encountered * @see #rethrowAnnotationConfigurationException */ static void handleIntrospectionFailure(AnnotatedElement element, Exception ex) { rethrowAnnotationConfigurationException(ex); Log loggerToUse = logger; if (loggerToUse == null) { loggerToUse = LogFactory.getLog(AnnotationUtils.class); logger = loggerToUse; } if (element instanceof Class && Annotation.class.isAssignableFrom((Class<?>) element)) { // Meta-annotation lookup on an annotation type if (loggerToUse.isDebugEnabled()) { loggerToUse.debug("Failed to introspect meta-annotations on [" + element + "]: " + ex); } } else { // Direct annotation lookup on regular Class, Method, Field if (loggerToUse.isInfoEnabled()) { loggerToUse.info("Failed to introspect annotations on [" + element + "]: " + ex); } } }
Example #14
Source File: JsonToStringConverter.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
@Override public boolean canConvert ( final Class<?> from, final Class<?> to, final AnnotatedElement annotatedElement ) { if ( !to.equals ( String.class ) ) { return false; } if ( from.isAnnotationPresent ( JSON.class ) ) { return true; } if ( annotatedElement != null && annotatedElement.isAnnotationPresent ( JSON.class ) ) { return true; } return false; }
Example #15
Source File: CDIBeanInfo.java From smallrye-metrics with Apache License 2.0 | 6 votes |
@Override public <T extends Annotation> AnnotationInfo getAnnotation(Class<T> metric) { T annotation = input.getAnnotation(metric); if (annotation != null) { return new CDIAnnotationInfoAdapter().convert(annotation); } else { // the metric annotation can also be applied via a stereotype, so look for stereotype annotations for (Annotation stereotypeCandidate : ((AnnotatedElement) input).getAnnotations()) { if (stereotypeCandidate.annotationType().isAnnotationPresent(Stereotype.class) && stereotypeCandidate.annotationType().isAnnotationPresent(metric)) { return new CDIAnnotationInfoAdapter().convert(stereotypeCandidate.annotationType().getAnnotation(metric)); } } return null; } }
Example #16
Source File: TypeMappedAnnotations.java From spring-analysis-note with MIT License | 5 votes |
private TypeMappedAnnotations(AnnotatedElement element, SearchStrategy searchStrategy, RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) { this.source = element; this.element = element; this.searchStrategy = searchStrategy; this.annotations = null; this.repeatableContainers = repeatableContainers; this.annotationFilter = annotationFilter; }
Example #17
Source File: AnnotatedElementUtils.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Determine if the supplied {@link AnnotatedElement} is annotated with * a <em>composed annotation</em> that is meta-annotated with an * annotation of the specified {@code annotationName}. * <p>This method follows <em>get semantics</em> as described in the * {@linkplain AnnotatedElementUtils class-level javadoc}. * @param element the annotated element * @param annotationType the annotation type on which to find meta-annotations * @return {@code true} if a matching meta-annotation is present * @since 4.2.3 * @see #getMetaAnnotationTypes */ public static boolean hasMetaAnnotationTypes(AnnotatedElement element, final Class<? extends Annotation> annotationType) { Assert.notNull(element, "AnnotatedElement must not be null"); Assert.notNull(annotationType, "annotationType must not be null"); return Boolean.TRUE.equals(searchWithGetSemantics(element, annotationType, null, new SimpleAnnotationProcessor<Boolean>() { @Override public Boolean process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) { boolean found = (annotation.annotationType() == annotationType); return (found && metaDepth > 0 ? Boolean.TRUE : CONTINUE); } })); }
Example #18
Source File: GraphQLSchemaBuilder.java From graphql-jpa with MIT License | 5 votes |
private boolean isNotIgnored(AnnotatedElement annotatedElement) { if (annotatedElement != null) { GraphQLIgnore schemaDocumentation = annotatedElement.getAnnotation(GraphQLIgnore.class); return schemaDocumentation == null; } return false; }
Example #19
Source File: MapOfChildResourcesInjector.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@Override public Object getValue(@NotNull Object adaptable, String name, @NotNull Type declaredType, @NotNull AnnotatedElement element, @NotNull DisposalCallbackRegistry callbackRegistry) { if (adaptable instanceof Resource) { boolean directDescendants = element.getAnnotation(DirectDescendants.class) != null; Resource source = ((Resource) adaptable); if (!directDescendants) { source = source.getChild(name); } return createMap(source != null ? source.getChildren() : Collections.EMPTY_LIST, declaredType); } else if (adaptable instanceof SlingHttpServletRequest) { return getValue(((SlingHttpServletRequest) adaptable).getResource(), name, declaredType, element, callbackRegistry); } return null; }
Example #20
Source File: RequestMappingHandlerMapping.java From spring-analysis-note with MIT License | 5 votes |
/** * Delegates to {@link #createRequestMappingInfo(RequestMapping, RequestCondition)}, * supplying the appropriate custom {@link RequestCondition} depending on whether * the supplied {@code annotatedElement} is a class or method. * @see #getCustomTypeCondition(Class) * @see #getCustomMethodCondition(Method) */ @Nullable private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) { RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class); RequestCondition<?> condition = (element instanceof Class ? getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element)); return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null); }
Example #21
Source File: ConverterManager.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
public <T> T convertTo ( final Object value, final Class<T> clazz, final AnnotatedElement targetElement ) throws ConversionException { return convertToByClass ( value, clazz, targetElement, () -> { final ConvertBy[] ann = targetElement.getAnnotationsByType ( ConvertBy.class ); if ( ann != null && ann.length > 0 ) { return Arrays.asList ( ann ).stream ().map ( ConvertBy::value ).collect ( Collectors.toList () ); } return null; } ); }
Example #22
Source File: ClassUtils.java From graphql-spqr with Apache License 2.0 | 5 votes |
public static String toString(AnnotatedElement element) { if (element instanceof Parameter) { return ((Parameter) element).getDeclaringExecutable() + "#" + ((Parameter) element).getName(); } if (element instanceof AnnotatedType) { return toString((AnnotatedType) element); } return element.toString(); }
Example #23
Source File: ComponentExtension.java From component-runtime with Apache License 2.0 | 5 votes |
@Override public void beforeAll(final ExtensionContext extensionContext) { final WithComponents element = AnnotationUtils .findAnnotation(extensionContext.getElement(), WithComponents.class) .orElseThrow(() -> new IllegalArgumentException( "No annotation @WithComponents on " + extensionContext.getRequiredTestClass())); this.packageName = element.value(); if (element.isolatedPackages().length > 0) { withIsolatedPackage(null, element.isolatedPackages()); } final boolean shouldUseEach = shouldIgnore(extensionContext.getElement()); if (!shouldUseEach) { doStart(extensionContext); } else if (!extensionContext.getElement().map(AnnotatedElement::getAnnotations).map(annotations -> { int componentIndex = -1; for (int i = 0; i < annotations.length; i++) { final Class<? extends Annotation> type = annotations[i].annotationType(); if (type == WithComponents.class) { componentIndex = i; } else if (type == Environment.class && componentIndex >= 0) { return false; } } return true; }).orElse(false)) { // check the ordering, if environments are put after this then the context is likely wrong // this condition is a simple heuristic but enough for most cases throw new IllegalArgumentException("If you combine @WithComponents and @Environment, you must ensure " + "environment annotations are becoming before the component one otherwise you will run in an " + "unexpected context and will not reproduce real execution."); } extensionContext.getStore(NAMESPACE).put(USE_EACH_KEY, shouldUseEach); extensionContext.getStore(NAMESPACE).put(SHARED_INSTANCE, this); }
Example #24
Source File: WebResourceFactory.java From JaxRSProviders with Apache License 2.0 | 5 votes |
private static WebTarget addPathFromAnnotation(final AnnotatedElement ae, WebTarget target) { final Path p = ae.getAnnotation(Path.class); if (p != null) { target = target.path(p.value()); } return target; }
Example #25
Source File: ClassMemberScaner.java From mPaaS with Apache License 2.0 | 5 votes |
/** 开始扫描 */ public void scan(Consumer<AnnotatedElement> consumer) { List<String> visited = new ArrayList<>(); if (scanMethod(consumer)) { return; } scanField(clazz, visited, consumer); }
Example #26
Source File: MultipleComposedAnnotationsOnSingleAnnotatedElementTests.java From java-technology-stack with MIT License | 5 votes |
private void assertFindAllMergedAnnotationsBehavior(AnnotatedElement element) { assertNotNull(element); Set<Cacheable> cacheables = findAllMergedAnnotations(element, Cacheable.class); assertNotNull(cacheables); assertEquals(2, cacheables.size()); Iterator<Cacheable> iterator = cacheables.iterator(); Cacheable fooCacheable = iterator.next(); Cacheable barCacheable = iterator.next(); assertEquals("fooKey", fooCacheable.key()); assertEquals("fooCache", fooCacheable.value()); assertEquals("barKey", barCacheable.key()); assertEquals("barCache", barCacheable.value()); }
Example #27
Source File: AbstractInjectableElement.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
private static String getSource(AnnotatedElement element) { Source source = ReflectionUtil.getAnnotation(element, Source.class); if (source != null) { return source.value(); } return null; }
Example #28
Source File: AnnotationUtils.java From spring-fabric-gateway with MIT License | 5 votes |
public static <A extends Annotation> AnnotatedElement getMethod(Class<?> clazz, Class<A> annotationType) { if (clazz == null || annotationType == null) { return null; } Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getAnnotation(annotationType) != null) { return method; } } return null; }
Example #29
Source File: WithAnnotationAcceptorTest.java From vraptor4 with Apache License 2.0 | 5 votes |
@Before public void setup() { MockitoAnnotations.initMocks(this); annotation = new Mirror() .on((AnnotatedElement) InterceptorWithCustomizedAccepts.class) .reflect().annotation(AcceptsWithAnnotations.class); }
Example #30
Source File: OrderUtils.java From spring-analysis-note with MIT License | 5 votes |
/** * Return the order from the specified annotations collection. * <p>Takes care of {@link Order @Order} and * {@code @javax.annotation.Priority}. * @param element the source element * @param annotations the annotation to consider * @return the order value, or {@code null} if none can be found */ @Nullable static Integer getOrderFromAnnotations(AnnotatedElement element, MergedAnnotations annotations) { if (!(element instanceof Class)) { return findOrder(annotations); } Object cached = orderCache.get(element); if (cached != null) { return (cached instanceof Integer ? (Integer) cached : null); } Integer result = findOrder(annotations); orderCache.put(element, result != null ? result : NOT_ANNOTATED); return result; }