java类java.lang.reflect.AnnotatedElement的实例源码

EditableUtils.java 文件源码 项目:gitplex-mit 阅读 74 收藏 0 点赞 0 评论 0
/**
 * Get display name of specified element from name parameter of {@link Editable} annotation. 
 * If the annotation is not defined or name parameter is not available in the annotation, the 
 * element name itself will be transferred to non-camel case and returned.
 *
 * @param element
 *          annotated element to get name from
 * @return
 *          display name of the element
 */
public static String getName(AnnotatedElement element) {
    Editable editable = element.getAnnotation(Editable.class);
    if (editable != null && editable.name().trim().length() != 0)
        return editable.name();
    else if (element instanceof Class)
        return WordUtils.uncamel(((Class<?>)element).getSimpleName());
    else if (element instanceof Field) 
        return WordUtils.uncamel(WordUtils.capitalize(((Field)element).getName()));
    else if (element instanceof Method)
        return StringUtils.substringAfter(WordUtils.uncamel(((Method)element).getName()), " ");
    else if (element instanceof Package) 
        return ((Package)element).getName();
    else
        throw new GeneralException("Invalid element type: " + element.getClass().getName());
}
InjectionPoint.java 文件源码 项目:elasticsearch_my 阅读 45 收藏 0 点赞 0 评论 0
private static <M extends Member & AnnotatedElement> void addInjectorsForMembers(
        TypeLiteral<?> typeLiteral, Factory<M> factory, boolean statics,
        Collection<InjectionPoint> injectionPoints, Errors errors) {
    for (M member : factory.getMembers(getRawType(typeLiteral.getType()))) {
        if (isStatic(member) != statics) {
            continue;
        }

        Inject inject = member.getAnnotation(Inject.class);
        if (inject == null) {
            continue;
        }

        try {
            injectionPoints.add(factory.create(typeLiteral, member, errors));
        } catch (ConfigurationException ignorable) {
            if (!inject.optional()) {
                errors.merge(ignorable.getErrorMessages());
            }
        }
    }
}
Configuration.java 文件源码 项目:OperatieBRP 阅读 51 收藏 0 点赞 0 评论 0
private static String getNameFromMemberAnnotation(final AnnotatedElement field) {
    final String result;
    if (field.isAnnotationPresent(Attribute.class)) {
        result = Utils.name(field.getAnnotation(Attribute.class).name(), field);
    } else if (field.isAnnotationPresent(Element.class)) {
        result = Utils.name(field.getAnnotation(Element.class).name(), field);
    } else if (field.isAnnotationPresent(ElementList.class)) {
        result = Utils.name(field.getAnnotation(ElementList.class).name(), field);
    } else if (field.isAnnotationPresent(ElementMap.class)) {
        result = Utils.name(field.getAnnotation(ElementMap.class).name(), field);
    } else if (field.isAnnotationPresent(Text.class)) {
        result = "**text**";
    } else {
        result = null;
    }
    return result;
}
FeatureUtil.java 文件源码 项目:guava-mock 阅读 32 收藏 0 点赞 0 评论 0
/**
 * Find all the tester annotations declared on a tester class or method.
 * @param classOrMethod a class or method whose tester annotations to find
 * @return an iterable sequence of tester annotations on the class
 */
public static Iterable<Annotation> getTesterAnnotations(AnnotatedElement classOrMethod) {
  synchronized (annotationCache) {
    List<Annotation> annotations = annotationCache.get(classOrMethod);
    if (annotations == null) {
      annotations = new ArrayList<Annotation>();
      for (Annotation a : classOrMethod.getDeclaredAnnotations()) {
        if (a.annotationType().isAnnotationPresent(TesterAnnotation.class)) {
          annotations.add(a);
        }
      }
      annotations = Collections.unmodifiableList(annotations);
      annotationCache.put(classOrMethod, annotations);
    }
    return annotations;
  }
}
QueriesInvocationHandler.java 文件源码 项目:queries 阅读 36 收藏 0 点赞 0 评论 0
private SourceId getSourceId(AnnotatedElement element) {
    SourceId sourceId = null;
    Optional<Annotation> sourceAnnotation = Stream.of(element.getAnnotations())
            .filter(a -> a.annotationType().isAnnotationPresent(RegisteredSourceIdProducer.class)).findFirst();

    if (sourceAnnotation.isPresent()) {
        RegisteredSourceIdProducer sourceIdProviderAnnotation = sourceAnnotation.get().annotationType()
                .getAnnotation(RegisteredSourceIdProducer.class);
        try {
            SourceIdProducer sourceIdProducer = sourceIdProviderAnnotation.value().newInstance();
            sourceId = sourceIdProducer.get(element, sourceAnnotation.get());
        } catch (Exception e) {
            throw new QueryProxyException("Problem with sourceId aquiring: can't find suitable constructor " + e,
                    e);
        }
    }
    return sourceId;
}
JpaMetamodelRedGProvider.java 文件源码 项目:redg 阅读 45 收藏 0 点赞 0 评论 0
private Map<String, String> getReferenceColumnNamesMapForReferenceAttribute(SingularAttribute<?, ?> attribute, ManagedType<?> targetEntity) {
    List<String> idAttributeNames = targetEntity.getSingularAttributes().stream()
               .filter(this::isIdAttribute)
               .map(this::getSingularAttributeColumnName)
               .collect(Collectors.toList());

    JoinColumns joinColumnsAnnotation =
               ((AnnotatedElement) attribute.getJavaMember()).getAnnotation(JoinColumns.class);
    JoinColumn joinColumnAnnotation =
               ((AnnotatedElement) attribute.getJavaMember()).getAnnotation(JoinColumn.class);
    JoinColumn[] joinColumns = joinColumnsAnnotation != null ? joinColumnsAnnotation.value() :
               joinColumnAnnotation != null ? new JoinColumn[]{joinColumnAnnotation} : null;
    Map<String, String> referenceColumnNamesMap;
    if (joinColumns != null) {
           referenceColumnNamesMap = Arrays.stream(joinColumns)
                   .collect(Collectors.toMap(JoinColumn::name, joinColumn ->
                           joinColumn.referencedColumnName().length() > 0 ? joinColumn.referencedColumnName() :
                                   idAttributeNames.get(0)));
       } else {
           referenceColumnNamesMap = idAttributeNames.stream()
                   .collect(Collectors.toMap(idAttributeName -> attribute.getName().toUpperCase() + "_"
                           + idAttributeName, idAttributeName -> idAttributeName));
       }
    return referenceColumnNamesMap;
}
CommonAnnotationBeanPostProcessor.java 文件源码 项目:lams 阅读 279 收藏 0 点赞 0 评论 0
public EjbRefElement(Member member, PropertyDescriptor pd) {
    super(member, pd);
    AnnotatedElement ae = (AnnotatedElement) member;
    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.equals(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();
}
ProviderSkeleton.java 文件源码 项目:jdk8u-jdk 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 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;
}
InjectionPoint.java 文件源码 项目:Elasticsearch 阅读 40 收藏 0 点赞 0 评论 0
private static <M extends Member & AnnotatedElement> void addInjectorsForMembers(
        TypeLiteral<?> typeLiteral, Factory<M> factory, boolean statics,
        Collection<InjectionPoint> injectionPoints, Errors errors) {
    for (M member : factory.getMembers(getRawType(typeLiteral.getType()))) {
        if (isStatic(member) != statics) {
            continue;
        }

        Inject inject = member.getAnnotation(Inject.class);
        if (inject == null) {
            continue;
        }

        try {
            injectionPoints.add(factory.create(typeLiteral, member, errors));
        } catch (ConfigurationException ignorable) {
            if (!inject.optional()) {
                errors.merge(ignorable.getErrorMessages());
            }
        }
    }
}
AnnotationUtils.java 文件源码 项目:holon-core 阅读 44 收藏 0 点赞 0 评论 0
/**
 * Find the annotations of given <code>annotationType</code> on given element and stores them in given
 * <code>accumulator</code>.
 * @param accumulator Accumulator
 * @param element Annotated element
 * @param annotationType Annotation type to lookup
 * @param repeatableContainerType Optional repeteable annotation type
 */
private static <A extends Annotation> void findAnnotations(List<A> accumulator, AnnotatedElement element,
        Class<A> annotationType, Class<? extends Annotation> repeatableContainerType) {

    // direct lookup
    A[] as = element.getAnnotationsByType(annotationType);
    if (as.length > 0) {
        for (A a : as) {
            accumulator.add(a);
        }
    }

    // check meta-annotations
    Annotation[] all = element.getAnnotations();
    if (all.length > 0) {
        for (Annotation annotation : all) {
            if (!isInJavaLangAnnotationPackage(annotation) && !annotation.annotationType().equals(annotationType)
                    && (repeatableContainerType == null
                            || !annotation.annotationType().equals(repeatableContainerType))) {
                findAnnotations(accumulator, annotation.annotationType(), annotationType, repeatableContainerType);
            }
        }
    }

}
Annotations.java 文件源码 项目:GitHub 阅读 49 收藏 0 点赞 0 评论 0
public Annotations(AnnotatedElement... elements) {
    for (AnnotatedElement element : elements) {
        for (Annotation annotation : element.getAnnotations()) {
            annotations.put(annotation.annotationType(), annotation);
        }
    }
}
ReflectionUtils.java 文件源码 项目:GitHub 阅读 53 收藏 0 点赞 0 评论 0
public static AnnotatedElement getAnnotatedElement(Class<?> beanClass, String propertyName, Class<?> propertyClass) {
    Field field = getFieldOrNull(beanClass, propertyName);
    Method method = getGetterOrNull(beanClass, propertyName, propertyClass);
    if (field == null || field.getAnnotations().length == 0) {
        return (method != null && method.getAnnotations().length > 0) ? method : method;
    } else if (method == null || method.getAnnotations().length == 0) {
        return field;
    } else {
        //return new Annotations(field, method);
        return null;
    }
}
TrackingInterceptor.java 文件源码 项目:Architecting-Modern-Java-EE-Applications 阅读 34 收藏 0 点赞 0 评论 0
private Tracked resolveAnnotation(InvocationContext context) {
    Function<AnnotatedElement, Tracked> extractor = c -> c.getAnnotation(Tracked.class);
    Method method = context.getMethod();

    Tracked tracked = extractor.apply(method);
    return tracked != null ? tracked : extractor.apply(method.getDeclaringClass());
}
AnnotationUtils.java 文件源码 项目:holon-core 阅读 39 收藏 0 点赞 0 评论 0
/**
 * Get all the annotations of given <code>annotationType</code> present in given <code>element</code>, including any
 * meta-annotation and supporting repeatable annotations.
 * @param <A> Annotation type
 * @param element Annotated element to inspect (not null)
 * @param annotationType Annotation type to lookup
 * @return List of detected annotation of given <code>annotationType</code>, an empty List if none found
 */
public static <A extends Annotation> List<A> getAnnotations(AnnotatedElement element, Class<A> annotationType) {
    ObjectUtils.argumentNotNull(element, "AnnotatedElement must be not null");
    ObjectUtils.argumentNotNull(annotationType, "Annotation type must be not null");

    Class<? extends Annotation> repeatableContainerType = null;
    if (annotationType.isAnnotationPresent(Repeatable.class)) {
        repeatableContainerType = annotationType.getAnnotation(Repeatable.class).value();
    }

    List<A> annotations = new LinkedList<>();
    findAnnotations(annotations, element, annotationType, repeatableContainerType);
    return annotations;
}
IntegerProvider.java 文件源码 项目:jfairy-junit-extension 阅读 41 收藏 0 点赞 0 评论 0
@Override
Object createFor(AnnotatedElement annotatedElement, Class<?> targetType, Fairy fairy) {
  IntegerWith config = findAnnotation(annotatedElement, IntegerWith.class).orElse(null);
  int min = minValue(config);
  int max = maxValue(config);

  BaseProducer producer = fairy.baseProducer();
  return producer.randomBetween(min, max);
}
QueriesInvocationHandler.java 文件源码 项目:queries 阅读 32 收藏 0 点赞 0 评论 0
private List<QueryConverter> getConverters(AnnotatedElement element) {
    List<QueryConverter> annotatedConverters = new ArrayList<>(2);
    List<Annotation> converterAnnotations = Stream.of(element.getAnnotations())
            .filter(a -> a.annotationType().isAnnotationPresent(Converter.class)
                    || converters.containsKey(a.annotationType()))
            .collect(Collectors.toList());
    if (!converterAnnotations.isEmpty()) {
        for (Annotation converterAnnotation : converterAnnotations) {
            QueryConverterFactory factory;
            if (converters.containsKey(converterAnnotation.annotationType())) {
                factory = converters.get(converterAnnotation.annotationType());
            } else {
                Converter converter = converterAnnotation.annotationType().getAnnotation(Converter.class);
                Class<? extends QueryConverterFactory> converterFactoryClass = converter.value();
                if (Converter.DEFAULT.class.isAssignableFrom(converterFactoryClass)) {
                    throw new QueryProxyException("Factory is not registered for annotation "
                            + converterAnnotation.annotationType().getName() + "! "
                            + "Set static converter using @Converter annotation value or use Queries.Builder.converter() method to register factory instance!");
                }
                try {
                    factory = converterFactoryClass.newInstance();
                } catch (Exception e) {
                    throw new QueryProxyException(
                            "Problem instantiating query converter factory class with no argument constructor " + e,
                            e);
                }
            }
            annotatedConverters.add(factory.get(converterAnnotation));
        }
    }
    return annotatedConverters;
}
TypeAnnotation.java 文件源码 项目:jdk8u-jdk 阅读 41 收藏 0 点赞 0 评论 0
public TypeAnnotation(TypeAnnotationTargetInfo targetInfo,
                      LocationInfo loc,
                      Annotation annotation,
                      AnnotatedElement baseDeclaration) {
    this.targetInfo = targetInfo;
    this.loc = loc;
    this.annotation = annotation;
    this.baseDeclaration = baseDeclaration;
}
FSWrapperTest.java 文件源码 项目:incubator-netbeans 阅读 52 收藏 0 点赞 0 评论 0
private static void checkAnnotations(AnnotatedElement el, AnnotatableWrapper aw) throws Exception {
    for (Annotation ann : el.getAnnotations()) {
        Annotation wrapper = aw.getAnnotation(ann.annotationType());

        assertNotNull(ann.annotationType().getName(), wrapper);

        checkAnnotation(ann, wrapper);
    }
}
RemoteObjectRegistrationImpl.java 文件源码 项目:NetCom2 阅读 40 收藏 0 点赞 0 评论 0
private boolean ignoreThrowable(Exception exception, AnnotatedElement... annotatedElements) {
    if(exception != null) {
        for(AnnotatedElement element : annotatedElements) {
            if(element == null) {
                continue;
            }
            IgnoreRemoteExceptions annotation = element.getAnnotation(IgnoreRemoteExceptions.class);
            if(annotation != null) {
                return !Arrays.asList(annotation.exceptTypes()).contains(exception.getClass());
            }
        }
    }
    return false;
}
InjectionPoint.java 文件源码 项目:elasticsearch_my 阅读 38 收藏 0 点赞 0 评论 0
private static <M extends Member & AnnotatedElement> void addInjectionPoints(TypeLiteral<?> type,
                                                                             Factory<M> factory, boolean statics, Collection<InjectionPoint> injectionPoints,
                                                                             Errors errors) {
    if (type.getType() == Object.class) {
        return;
    }

    // Add injectors for superclass first.
    TypeLiteral<?> superType = type.getSupertype(type.getRawType().getSuperclass());
    addInjectionPoints(superType, factory, statics, injectionPoints, errors);

    // Add injectors for all members next
    addInjectorsForMembers(type, factory, statics, injectionPoints, errors);
}
AllureJunit5AnnotationProcessor.java 文件源码 项目:allure-java 阅读 47 收藏 0 点赞 0 评论 0
private List<Label> getLabels(final AnnotatedElement annotatedElement) {
    return Stream.of(
            getAnnotations(annotatedElement, Epic.class).map(ResultsUtils::createLabel),
            getAnnotations(annotatedElement, Feature.class).map(ResultsUtils::createLabel),
            getAnnotations(annotatedElement, Story.class).map(ResultsUtils::createLabel),
            getAnnotations(annotatedElement, Severity.class).map(ResultsUtils::createLabel),
            getAnnotations(annotatedElement, Owner.class).map(ResultsUtils::createLabel)
    ).reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList());
}
AllureJunit5AnnotationProcessor.java 文件源码 项目:allure-java 阅读 53 收藏 0 点赞 0 评论 0
private List<Link> getLinks(final AnnotatedElement annotatedElement) {
    return Stream.of(
            getAnnotations(annotatedElement, io.qameta.allure.Link.class).map(ResultsUtils::createLink),
            getAnnotations(annotatedElement, io.qameta.allure.Issue.class).map(ResultsUtils::createLink),
            getAnnotations(annotatedElement, io.qameta.allure.TmsLink.class).map(ResultsUtils::createLink))
            .reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList());
}
AllureJunit5AnnotationProcessor.java 文件源码 项目:allure-java 阅读 44 收藏 0 点赞 0 评论 0
private <T extends Annotation> Stream<T> getAnnotations(final AnnotatedElement annotatedElement,
                                                        final Class<T> annotationClass) {
    final T annotation = annotatedElement.getAnnotation(annotationClass);
    return Stream.concat(
            extractRepeatable(annotatedElement, annotationClass).stream(),
            Objects.isNull(annotation) ? Stream.empty() : Stream.of(annotation)
    );
}
Allure1Utils.java 文件源码 项目:allure-java 阅读 36 收藏 0 点赞 0 评论 0
private static <T extends Annotation> List<Label> getLabels(final AnnotatedElement element,
                                                            final Class<T> annotation,
                                                            final Function<T, List<Label>> extractor) {
    return element.isAnnotationPresent(annotation)
            ? extractor.apply(element.getAnnotation(annotation))
            : Collections.emptyList();
}
Allure1Utils.java 文件源码 项目:allure-java 阅读 39 收藏 0 点赞 0 评论 0
public static <T extends Annotation> List<Link> getLinks(final Method method, final Class<T> annotation,
                                                         final Function<T, List<Link>> extractor) {
    final List<Link> labels = new ArrayList<>();
    labels.addAll(getLinks((AnnotatedElement) method, annotation, extractor));
    labels.addAll(getLinks(method.getDeclaringClass(), annotation, extractor));
    return labels;
}
FairyExtension.java 文件源码 项目:jfairy-junit-extension 阅读 74 收藏 0 点赞 0 评论 0
private Object resolve(AnnotatedElement annotatedElement, Class<?> targetType) {
  for (ObjectProvider provider : providers) {
    if (provider.supports(targetType)) {
      return provider.createFor(annotatedElement, targetType);
    }
  }

  throw new IllegalArgumentException("no provider found for type " + targetType);
}
DisabledCondition.java 文件源码 项目:bach 阅读 49 收藏 0 点赞 0 评论 0
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
  AnnotatedElement element = extensionContext.getElement().orElseThrow(AssertionError::new);
  Disabled disabled = findAnnotation(element, Disabled.class).orElseThrow(AssertionError::new);
  String name = disabled.value();
  String reason = name + "=" + System.getProperty(name);
  boolean result = Boolean.getBoolean(name);
  if (disabled.not()) {
    result = !result;
  }
  if (result) {
    return ConditionEvaluationResult.disabled(reason);
  }
  return ConditionEvaluationResult.enabled(reason);
}
AnnotationFinder.java 文件源码 项目:micrometer 阅读 41 收藏 0 点赞 0 评论 0
/**
 * The default implementation performs a simple search for a declared annotation matching the search type.
 * Spring provides a more sophisticated annotation search utility that matches on meta-annotations as well.
 *
 * @param annotatedElement The element to search.
 * @param annotationType The annotation type class.
 * @param <A> Annotation type to search for.
 * @return
 */
@SuppressWarnings("unchecked")
default <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) {
    Annotation[] anns = annotatedElement.getDeclaredAnnotations();
    for (Annotation ann : anns) {
        if (ann.annotationType() == annotationType) {
            return (A) ann;
        }
    }
    return null;
}
TimedFinder.java 文件源码 项目:micrometer 阅读 43 收藏 0 点赞 0 评论 0
Set<Timed> findTimedAnnotations(AnnotatedElement element) {
    Timed t = annotationFinder.findAnnotation(element, Timed.class);
    if (t != null)
        return Collections.singleton(t);

    TimedSet ts = annotationFinder.findAnnotation(element, TimedSet.class);
    if (ts != null) {
        return Arrays.stream(ts.value()).collect(Collectors.toSet());
    }

    return Collections.emptySet();
}
TimedUtils.java 文件源码 项目:micrometer 阅读 42 收藏 0 点赞 0 评论 0
public static Set<Timed> findTimedAnnotations(AnnotatedElement element) {
    Timed t = AnnotationUtils.findAnnotation(element, Timed.class);
    if (t != null)
        return Collections.singleton(t);

    TimedSet ts = AnnotationUtils.findAnnotation(element, TimedSet.class);
    if (ts != null) {
        return Arrays.stream(ts.value()).collect(Collectors.toSet());
    }

    return Collections.emptySet();
}


问题


面经


文章

微信
公众号

扫码关注公众号