Java 类java.lang.annotation.Annotation 实例源码

项目:primeval-reflex    文件:RepeatedAnnotationObjectInterceptor.java   
private static <A extends Annotation, E extends Throwable> char callChar(
        AnnotationInterceptor<A> annotationInterceptor,
        int annotationId, A[] annotations, CallContext context, Arguments currentArguments,
        ToCharFunction<Arguments> terminalInvokeFun) throws E {

    A annotation = annotations[annotationId];
    if (annotationId == annotations.length - 1) { // last annotation
        return annotationInterceptor.onCall(annotation, context,
                new SimpleCharInterceptionHandler(currentArguments, terminalInvokeFun));
    } else {
        return annotationInterceptor.onCall(annotation, context,
                new SimpleCharInterceptionHandler(currentArguments,
                        (args) -> callChar(annotationInterceptor, annotationId + 1, annotations, context, args,
                                terminalInvokeFun)));
    }
}
项目:nymph    文件:ScannerNymphBeans.java   
/**
 * 解析jar包中的类
 * @param jarFile           表示jar文件
 * @param packageLocation   扫描的包路径
 * @throws Exception 反射时的异常
 */
private void resolveJar(JarFile jarFile, String packageLocation) throws Exception {
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        String classLocation = entries.nextElement().getName();
        // 当jar文件中的路径是以packageLocation指定的路径开头,并且是以.class结尾时
        if (classLocation.startsWith(packageLocation) && classLocation.endsWith(".class")) {
            String location = classLocation.replace(".class", "").replace("/", ".");
            Class<?> forName = Class.forName(location);
            configurationBeansHandler(forName);
            Annotation[] annos = forName.getAnnotations();
            if (AnnoUtil.exist(annos, Bean.class) && !forName.isInterface()) {
                beansInitializedHandler(forName);
            }
        }
    }
}
项目:OpenJSharp    文件:TypeInfo.java   
public TypeInfo(QName tagName, Type type, Annotation... annotations) {
        if(tagName==null || type==null || annotations==null) {
            String nullArgs = "";

            if(tagName == null)     nullArgs = "tagName";
            if(type == null)        nullArgs += (nullArgs.length() > 0 ? ", type" : "type");
            if(annotations == null) nullArgs += (nullArgs.length() > 0 ? ", annotations" : "annotations");

//            Messages.ARGUMENT_CANT_BE_NULL.format(nullArgs);

            throw new IllegalArgumentException( "Argument(s) \"" + nullArgs + "\" can''t be null.)");
        }

        this.tagName = new QName(tagName.getNamespaceURI().intern(), tagName.getLocalPart().intern(), tagName.getPrefix());
        this.type = type;
        if (type instanceof Class && ((Class<?>)type).isPrimitive()) nillable = false;
        this.annotations = annotations;
    }
项目:dropwizard-vavr    文件:ValueMessageBodyWriter.java   
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public void writeTo(Value<?> entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream)
        throws IOException {
    final Object entityValue = entity.getOrElseThrow(() -> EmptyValueException.INSTANCE);
    final Class<?> entityClass = entityValue.getClass();

    final Type actualGenericTypeArgument;
    if (genericType instanceof ParameterizedType) {
        actualGenericTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[0];
    } else {
        actualGenericTypeArgument = entityClass;
    }

    final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entityClass, actualGenericTypeArgument, annotations, mediaType);
    writer.writeTo(entityValue, entityClass, actualGenericTypeArgument, annotations, mediaType, httpHeaders, entityStream);
}
项目:Elasticsearch    文件:Elements.java   
private <T> AnnotatedElementBuilder exposeInternal(Key<T> key) {
    if (privateElements == null) {
        addError("Cannot expose %s on a standard binder. "
                + "Exposed bindings are only applicable to private binders.", key);
        return new AnnotatedElementBuilder() {
            @Override
            public void annotatedWith(Class<? extends Annotation> annotationType) {
            }

            @Override
            public void annotatedWith(Annotation annotation) {
            }
        };
    }

    ExposureBuilder<T> builder = new ExposureBuilder<>(this, getSource(), key);
    privateElements.addExposureBuilder(builder);
    return builder;
}
项目:vertx-zero    文件:Anno.java   
/**
 * Query clazz's methods to getPlugin all annotated spec annotations.
 *
 * @param clazz
 * @param methodCls
 * @return
 */
public static Annotation[] query(final Class<?> clazz,
                                 final Class<? extends Annotation> methodCls) {
    return Fn.get(() -> {
        final Method[] methods = clazz.getDeclaredMethods();
        final List<Method> methodSet = Arrays.asList(methods);
        final List<Method> result = methodSet.stream()
                .filter(item -> item.isAnnotationPresent(methodCls))
                .collect(Collectors.toList());
        final List<Annotation> resultAnnos = new ArrayList<>();
        for (final Method method : result) {
            final Annotation anno = method.getAnnotation(methodCls);
            if (null != anno) {
                resultAnnos.add(anno);
            }
        }
        return resultAnnos.toArray(new Annotation[]{});
    }, clazz, methodCls);
}
项目:SwiftModule    文件:IntentMethod.java   
private Bundle prepareBundle(Object[] args) {
  Bundle bundle = new Bundle();
  int paramCount = parameterTypes.length;
  if (parameterTypes != null && paramCount > 0){
    for (int i = 0; i < paramCount; i++) {
      String key;
      Annotation[] paramAnnotations = parameterAnnotationsArray[i];
      for (Annotation anno: paramAnnotations) {
        if (anno instanceof Key){
          key = ((Key) anno).value();
          handleParams(bundle, key, parameterTypes[i], args[i]);
        }else if(anno instanceof FieldMap){

        }else{
          throw new IllegalStateException("不支持的参数注解: " + anno.toString() );
        }
      }
    }
  }
  return bundle;
}
项目:beadledom    文件:FilteringJacksonJsonProvider.java   
@Override
public void writeTo(
    Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException {
  String fields = uriInfo.getQueryParameters() == null ? null
      : uriInfo.getQueryParameters().getFirst("fields");

  FieldFilter fieldFilter = FieldFilter.create(fields);
  if (!fieldFilter.hasFilters()) {
    super.writeTo(o, type, genericType, annotations, mediaType, httpHeaders, os);
    return;
  }

  JsonGenerator jgen = objectMapper.getFactory().createGenerator(os);
  TokenBuffer tokenBuffer = new TokenBuffer(objectMapper, false);
  objectMapper.writeValue(tokenBuffer, o);
  JsonParser jsonParser = tokenBuffer.asParser();
  fieldFilter.writeJson(jsonParser, jgen);
  jgen.flush();
}
项目:OpenJSharp    文件:ExternalMetadataReader.java   
private Annotation[] doMerge(Annotation[] annotations, Annotation[] externalAnnotations) {
    HashMap<String, Annotation> mergeMap = new HashMap<String, Annotation>();
    if (annotations != null) {
        for (Annotation reflectionAnnotation : annotations) {
            mergeMap.put(reflectionAnnotation.annotationType().getName(), reflectionAnnotation);
        }
    }

    // overriding happens here, based on annotationType().getName() ...
    if (externalAnnotations != null) {
        for (Annotation externalAnnotation : externalAnnotations) {
            mergeMap.put(externalAnnotation.annotationType().getName(), externalAnnotation);
        }
    }
    Collection<Annotation> values = mergeMap.values();
    int size = values.size();
    return size == 0 ? null : values.toArray(new Annotation[size]);
}
项目:syndesis    文件:SyndesisExtensionActionProcessor.java   
protected void writeIfNotEmpty(Properties prop, String key, Object value) throws InvocationTargetException, IllegalAccessException {
    if(value != null && !"".equals(value.toString().trim())) {
        if(value instanceof String[]){
            String[] arr = (String[])value;
            if(arr.length > 0){
                prop.put(key, String.join(",", arr));
            }
        } else if(Object[].class.isInstance(value)) {
            Object[] array = (Object[]) value;
            for (int i=0; i<array.length; i++) {
                if (propertyEnumAnnotationClass.isInstance(array[i])) {
                    Annotation enumAnn = (Annotation) array[i];
                    Properties props = gatherProperties(enumAnn, propertyEnumAnnotationClass);
                    for (String propName : props.stringPropertyNames()) {
                        prop.put(key + "[" + i + "]." + propName, props.getProperty(propName));
                    }
                }
            }
        } else {
            prop.put(key, value.toString());
        }
    }
}
项目:teasy    文件:MethodsInvoker.java   
protected TestClassContext(Class testClass, AbstractTest testInstance, Class<? extends Annotation> annotationClassToInvokeMethods, ITestContext testContext) {
    this.testClass = testClass;
    this.testInstance = testInstance;
    this.annotationClassToInvokeMethods = annotationClassToInvokeMethods;
    if (testContext.getExcludedGroups() == null) {
        this.excludedGroups = new String[0];
    } else {
        this.excludedGroups = Arrays.copyOf(testContext.getExcludedGroups(), testContext.getExcludedGroups().length);
    }
    if (testContext.getIncludedGroups() == null) {
        this.includedGroups = new String[0];
    } else {
        this.includedGroups = Arrays.copyOf(testContext.getIncludedGroups(), testContext.getIncludedGroups().length);
    }
    this.testContext = testContext;
}
项目:vertx-zero    文件:AffluxThread.java   
private void scanSpecific(final Field field) {
    // Vert.x Defined
    final Set<Class<? extends Annotation>> defineds
            = Plugins.INFIX_MAP.keySet();
    final Annotation[] annotations = field.getDeclaredAnnotations();
    // Annotation counter
    final Set<String> set = new HashSet<>();
    final Annotation hitted = Observable.fromArray(annotations)
            .filter(annotation -> defineds.contains(annotation.annotationType()))
            .map(annotation -> {
                set.add(annotation.annotationType().getName());
                return annotation;
            }).blockingFirst();
    // Duplicated annotated
    Fn.flingUp(Values.ONE < set.size(), LOGGER,
            MultiAnnotatedException.class, getClass(),
            field.getName(), field.getDeclaringClass().getName(), set);
    // Fill typed directly.
    LOGGER.info(Info.SCANED_FIELD, this.reference,
            field.getName(),
            field.getDeclaringClass().getName(),
            hitted.annotationType().getName());
    this.fieldMap.put(field.getName(), field.getType());
}
项目:polymorphia    文件:TypesModel.java   
public TypesModel(final Set<Class<?>> classes, final Set<String> packages, final Set<Class<? extends Annotation>> ignoreAnnotations) {
    this.ignoreAnnotations = ignoreAnnotations != null ? ignoreAnnotations : Collections.emptySet();

    // first index all direct classes
    if (classes != null) {
        for (Class<?> aClass : classes) {
            indexClass(aClass);
        }
    }

    if (packages != null && !packages.isEmpty()) {
        Indexer indexer = getIndexer();
        for (String aPackage : packages) {
            for (Class<?> clazz : indexer.getClassesForPackage(aPackage)) {
                indexClass(clazz);
            }
        }
    }
    this.classHierarchy = buildClassHierarchy(allClasses);
}
项目:spring-jdbc-orm    文件:ReflectionUtils.java   
/**
 * 获取constructors数组中匹配的annotationClass注解
 *
 * @param constructors    constructor对象数组
 * @param annotationClass annotationClass注解
 * @return List
 */
public static <T extends Annotation> List<T> getAnnotations(
        Constructor[] constructors, Class annotationClass) {

    if (isEmpty(constructors)) {
        return null;
    }

    List<T> result = new ArrayList<T>();

    for (Constructor constructor : constructors) {
        Annotation annotation = getAnnotation(constructor, annotationClass);
        if (annotation != null) {
            result.add((T) annotation);
        }
    }

    return result;
}
项目:GitHub    文件:RetrofitTest.java   
@Test public void responseConverterFactoryQueried() {
  Type type = String.class;
  Annotation[] annotations = new Annotation[0];

  Converter<ResponseBody, ?> expectedAdapter = mock(Converter.class);
  Converter.Factory factory = mock(Converter.Factory.class);

  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("http://example.com/")
      .addConverterFactory(factory)
      .build();

  doReturn(expectedAdapter).when(factory).responseBodyConverter(type, annotations, retrofit);

  Converter<ResponseBody, ?> actualAdapter = retrofit.responseBodyConverter(type, annotations);
  assertThat(actualAdapter).isSameAs(expectedAdapter);

  verify(factory).responseBodyConverter(type, annotations, retrofit);
  verifyNoMoreInteractions(factory);
}
项目:hadoop    文件:AdminSecurityInfo.java   
@Override
public KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf) {
  if (!protocol.equals(ResourceManagerAdministrationProtocolPB.class)) {
    return null;
  }
  return new KerberosInfo() {

    @Override
    public Class<? extends Annotation> annotationType() {
      return null;
    }

    @Override
    public String serverPrincipal() {
      return YarnConfiguration.RM_PRINCIPAL;
    }

    @Override
    public String clientPrincipal() {
      return null;
    }
  };
}
项目:lams    文件:JPAOverriddenAnnotationReader.java   
/**
 * Adds a @MapKeyEnumerated annotation to the specified annotationList if the specified element
 * contains a map-key-enumerated sub-element. This should only be the case for
 * element-collection, many-to-many, or one-to-many associations.
 */
private void getMapKeyEnumerated(List<Annotation> annotationList, Element element) {
    Element subelement = element != null ? element.element( "map-key-enumerated" ) : null;
    if ( subelement != null ) {
        AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyEnumerated.class );
        EnumType value = EnumType.valueOf( subelement.getTextTrim() );
        ad.setValue( "value", value );
        annotationList.add( AnnotationFactory.create( ad ) );
    }
}
项目:GPigValidator    文件:SizeValidator.java   
@Override
public boolean isCorrect(Object objectValue, Annotation annotation) {
    if (areWrongPreconditions(objectValue, annotation))
        return false;

    Size sizeAnnotation = (Size) annotation;

    int size = getSize(objectValue);
    return sizeAnnotation.min() <= size && size <= sizeAnnotation.max();
}
项目:GitHub    文件:AnnotatedConverters.java   
@Override public Converter<?, RequestBody> requestBodyConverter(Type type,
    Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
  for (Annotation annotation : parameterAnnotations) {
    Converter.Factory factory = factories.get(annotation.annotationType());
    if (factory != null) {
      return factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations,
          retrofit);
    }
  }
  return null;
}
项目:GitHub    文件:Retrofit.java   
/**
 * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
 * {@linkplain #converterFactories() factories} except {@code skipPast}.
 *
 * @throws IllegalArgumentException if no converter available for {@code type}.
 */
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(Converter.Factory skipPast,
    Type type, Annotation[] annotations) {
  checkNotNull(type, "type == null");
  checkNotNull(annotations, "annotations == null");

  int start = converterFactories.indexOf(skipPast) + 1;
  for (int i = start, count = converterFactories.size(); i < count; i++) {
    Converter<ResponseBody, ?> converter =
        converterFactories.get(i).responseBodyConverter(type, annotations, this);
    if (converter != null) {
      //noinspection unchecked
      return (Converter<ResponseBody, T>) converter;
    }
  }

  StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ")
      .append(type)
      .append(".\n");
  if (skipPast != null) {
    builder.append("  Skipped:");
    for (int i = 0; i < start; i++) {
      builder.append("\n   * ").append(converterFactories.get(i).getClass().getName());
    }
    builder.append('\n');
  }
  builder.append("  Tried:");
  for (int i = start, count = converterFactories.size(); i < count; i++) {
    builder.append("\n   * ").append(converterFactories.get(i).getClass().getName());
  }
  throw new IllegalArgumentException(builder.toString());
}
项目:GitHub    文件:FastJsonProvider.java   
/**
 * Method that JAX-RS container calls to try to check whether values of
 * given type (and media type) can be deserialized by this provider.
 */
public boolean isReadable(Class<?> type, //
                          Type genericType, //
                          Annotation[] annotations, //
                          MediaType mediaType) {

    if (!hasMatchingMediaType(mediaType)) {
        return false;
    }

    return isValidType(type, annotations);
}
项目:lams    文件:ClassUtils.java   
public static boolean isAnnotationPresent(Class<?> clazz, Class<? extends Annotation> a) {
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        if (c.isAnnotationPresent(a))
            return true;
        if(isAnnotationPresentOnInterfaces(c, a))
            return true;
    }
    return false;
}
项目:xtf    文件:MsaProfileFilter.java   
@Override
public boolean exclude(final Class<?> testClass) {
    for (final Annotation annotation : Arrays.asList(testClass.getAnnotations())) {
        if (annotation instanceof VertxProfile && "vertx".equals(this.msaProvider)) {
            return false;
        } else if (annotation instanceof SpringBootProfile && "springboot".equals(this.msaProvider)) {
            return false;
        } else if (annotation instanceof WildFlySwarmProfile && "wildfly-swarm".equals(this.msaProvider)) {
            return false;
        } else if (annotation instanceof JavaS2IProfile && "java-s2i".equals(this.msaProvider)) {
            return false;
        }
    }
    return true;
}
项目:vertx-zero    文件:AffluxThread.java   
private void scanQualifier(final Field field,
                           final List<Class<?>> instanceCls) {
    // Field must annotated with @Qualifier
    final Annotation annotation = field.getAnnotation(Qualifier.class);

    Fn.flingUp(null == annotation,
            LOGGER, QualifierMissedException.class,
            getClass(), field.getName(), field.getDeclaringClass().getName());

    // All implementation class must be annotated with @Named
    final boolean match = instanceCls.stream()
            .allMatch(item -> item.isAnnotationPresent(Named.class));

    final Set<String> names = instanceCls.stream()
            .map(Class::getName).collect(Collectors.toSet());

    Fn.flingUp(!match,
            LOGGER, NamedImplementionException.class,
            getClass(), names, field.getType().getName());

    // Named value must be reflect with @Qualifier
    final String value = Instance.invoke(annotation, "value");

    final Optional<Class<?>> verified = instanceCls.stream()
            .filter(item -> {
                final Annotation target = item.getAnnotation(Named.class);
                final String targetValue = Instance.invoke(target, "value");
                return value.equals(targetValue)
                        && !StringUtil.isNil(targetValue);
            }).findAny();

    Fn.flingUp(!verified.isPresent(),
            LOGGER, NamedNotFoundException.class,
            getClass(), names, value);

    // Passed all specification
    this.fieldMap.put(field.getName(), verified.get());
}
项目:garlicts    文件:BeanLoaderTemplate.java   
/**
 * 获取包名下带有某注解的所有类 
 */
public List<Class<?>> getBeanClassListByAnnotation(Class<? extends Annotation> annotationClass) {

    List<Class<?>> classList = new ArrayList<Class<?>>();
    Map<Class<?>,Object> beanMap = BeanContainerAbility.getBeanMap();

       for (Class<?> cls : beanMap.keySet()) {
           if (cls.isAnnotationPresent(annotationClass)) {
            classList.add(cls);
           }
       }
       return classList;

}
项目:super-volley    文件:DeserializeErrorBody.java   
public static void main(String... args) throws IOException {
    // Create our Service instance with a SuperVolley pointing at the local web server and Gson.
    SuperVolley volley = new SuperVolley.Builder()
            .baseUrl(Constants.API_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // Create a MockSuperVolley object with a NetworkBehavior which manages the fake behavior of calls.
    NetworkBehavior behavior = NetworkBehavior.create();
    MockSuperVolley mockSuperVolley = new MockSuperVolley.Builder(volley)
            .networkBehavior(behavior)
            .build();

    BehaviorDelegate<Service> delegate = mockSuperVolley.create(Service.class);
    MockService service = new MockService(delegate);

    Call<Void> call = service.getUser();

    Response<Void> response = call.execute();

    // Normally you would check response.isSuccess() here before doing the following, but we know
    // this call will always fail. You could also use response.code() to determine whether to
    // convert the error body and/or which type to use for conversion.

    // Look up a converter for the Error type on the SuperVolley instance.
    Converter<ResponseBody, Error> errorConverter =
            volley.responseBodyConverter(Error.class, new Annotation[0]);
    // Convert the error body into our Error type.
    Error error = errorConverter.convert(response.errorBody());
    System.out.println("ERROR: " + error.message);
}
项目:oscm    文件:ReflectiveClone.java   
private static boolean needsToCascade(Field field) {
    Class<?> fieldtype = field.getType();
    if (!DomainObject.class.isAssignableFrom(fieldtype))
        return false;
    Annotation ann;
    CascadeType[] cascades = null;
    ann = field.getAnnotation(OneToOne.class);
    if (ann != null) {
        cascades = ((OneToOne) ann).cascade();
    } else {
        ann = field.getAnnotation(OneToMany.class);
        if (ann != null) {
            cascades = ((OneToMany) ann).cascade();
        } else {
            ann = field.getAnnotation(ManyToOne.class);
            if (ann != null) {
                cascades = ((ManyToOne) ann).cascade();
            } else {
                ann = field.getAnnotation(ManyToMany.class);
                if (ann != null) {
                    cascades = ((ManyToMany) ann).cascade();
                }
            }
        }
    }
    if (cascades == null)
        return false;
    for (CascadeType cas : cascades) {
        if ((cas == CascadeType.ALL) || (cas == CascadeType.MERGE)
                || (cas == CascadeType.PERSIST)
                || (cas == CascadeType.REMOVE)) {
            return true;
        }
    }
    return false;
}
项目:OpenJSharp    文件:TypeReference.java   
/**
 * Finds the specified annotation from the array and returns it.
 * Null if not found.
 */
public <A extends Annotation> A get( Class<A> annotationType ) {
    for (Annotation a : annotations) {
        if(a.annotationType()==annotationType)
            return annotationType.cast(a);
    }
    return null;
}
项目:lams    文件:JPAOverriddenAnnotationReader.java   
private void buildMapKeyJoinColumns(List<Annotation> annotationList, Element element) {
    MapKeyJoinColumn[] joinColumns = getMapKeyJoinColumns( element );
    if ( joinColumns.length > 0 ) {
        AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyJoinColumns.class );
        ad.setValue( "value", joinColumns );
        annotationList.add( AnnotationFactory.create( ad ) );
    }
}
项目:bootstrap    文件:NotFoundResponseFilterTest.java   
@Test
public void filterNoAnnotation() {
    final ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class);
    final ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class);
    Mockito.when(responseContext.getStatus()).thenReturn(204);
    final Annotation[] annotations = new Annotation[] {};
    Mockito.when(responseContext.getEntityAnnotations()).thenReturn(annotations);
    filter.filter(requestContext, responseContext);
}
项目:OpenJSharp    文件:Symbol.java   
@Override
protected <A extends Annotation> A[] getInheritedAnnotations(Class<A> annoType) {

    ClassSymbol sup = getSuperClassToSearchForAnnotations();

    return sup == null ? super.getInheritedAnnotations(annoType)
                       : sup.getAnnotationsByType(annoType);
}
项目:GitHub    文件:AnnotatedConverters.java   
public Builder add(Class<? extends Annotation> cls, Converter.Factory factory) {
  if (cls == null) {
    throw new NullPointerException("cls == null");
  }
  if (factory == null) {
    throw new NullPointerException("factory == null");
  }
  factories.put(cls, factory);
  return this;
}
项目:lams    文件:JPAOverriddenAnnotationReader.java   
private Annotation getConvertsForAttribute(List<Element> elementsForProperty, XMLContext.Default defaults) {
    // NOTE : we use a map here to make sure that an xml and annotation referring to the same attribute
    // properly overrides.  Very sparse map, yes, but easy setup.
    // todo : revisit this
    // although bear in mind that this code is no longer used in 5.0...

    final Map<String,Convert> convertAnnotationsMap = new HashMap<String, Convert>();

    for ( Element element : elementsForProperty ) {
        final boolean isBasic = "basic".equals( element.getName() );
        final boolean isEmbedded = "embedded".equals( element.getName() );

        // todo : can be collections too

        final boolean canHaveConverts = isBasic || isEmbedded;

        if ( !canHaveConverts ) {
            continue;
        }

        final String attributeNamePrefix = isBasic ? null : propertyName;
        applyXmlDefinedConverts( element, defaults, attributeNamePrefix, convertAnnotationsMap );
    }

    // NOTE : per section 12.2.3.16 of the spec <convert/> is additive, although only if "metadata-complete" is not
    // specified in the XML

    if ( defaults.canUseJavaAnnotations() ) {
        // todo : note sure how to best handle attributeNamePrefix here
        applyPhysicalConvertAnnotations( propertyName, convertAnnotationsMap );
    }

    if ( !convertAnnotationsMap.isEmpty() ) {
        final AnnotationDescriptor groupingDescriptor = new AnnotationDescriptor( Converts.class );
        groupingDescriptor.setValue( "value", convertAnnotationsMap.values().toArray( new Convert[convertAnnotationsMap.size()]) );
        return AnnotationFactory.create( groupingDescriptor );
    }

    return null;
}
项目:GitHub    文件:BehaviorDelegate.java   
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <R> T returning(Call<R> call) {
  final Call<R> behaviorCall = new BehaviorCall<>(behavior, executor, call);
  return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service },
      new InvocationHandler() {
        @Override
        public T invoke(Object proxy, Method method, Object[] args) throws Throwable {
          Type returnType = method.getGenericReturnType();
          Annotation[] methodAnnotations = method.getAnnotations();
          CallAdapter<R, T> callAdapter =
              (CallAdapter<R, T>) retrofit.callAdapter(returnType, methodAnnotations);
          return callAdapter.adapt(behaviorCall);
        }
      });
}
项目:XSnow    文件:GsonConverterFactory.java   
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    if (type != null && type.equals(String.class)) {
        return new JsonResponseBodyConverter<>();
    }
    TypeAdapter<?> adapter = null;
    if (type != null) {
        adapter = gson.getAdapter(TypeToken.get(type));
    }
    return new GsonResponseBodyConverter<>(gson, adapter);
}
项目:Elasticsearch    文件:MapBinder.java   
/**
 * Returns a new mapbinder that collects entries of {@code keyType}/{@code valueType} in a
 * {@link Map} that is itself bound with {@code annotation}.
 */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder,
                                                  TypeLiteral<K> keyType, TypeLiteral<V> valueType, Annotation annotation) {
    binder = binder.skipSources(MapBinder.class, RealMapBinder.class);
    return newMapBinder(binder, valueType,
            Key.get(mapOf(keyType, valueType), annotation),
            Key.get(mapOfProviderOf(keyType, valueType), annotation),
            Multibinder.newSetBinder(binder, entryOfProviderOf(keyType, valueType), annotation));
}
项目:bootstrap    文件:UnixTimestampParameterHandler.java   
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType, final Annotation[] annotations) { // NOSONAR

    // Basic date handler
    if (rawType.equals(Date.class)) {
        return (ParamConverter<T>) converter;
    }

    // LocalDate handler
    if (rawType.equals(LocalDate.class)) {
        return (ParamConverter<T>) localDateconverter;
    }
    return null;
}
项目:Reer    文件:AbstractMultiTestRunner.java   
public <A extends Annotation> A getAnnotation(Class<A> type) {
    A annotation = test.getAnnotation(type);
    if (annotation != null) {
        return annotation;
    }
    return parent.getAnnotation(type);
}
项目:OpenJSharp    文件:ClassInfoImpl.java   
/**
 * Gets an annotation that are allowed on both class and type.
 */
private <T extends Annotation> T getClassOrPackageAnnotation(Class<T> type) {
    T t = reader().getClassAnnotation(type,clazz,this);
    if(t!=null)
        return t;
    // defaults to the package level
    return reader().getPackageAnnotation(type,clazz,this);
}
项目:GPigValidator    文件:SizeValidator.java   
@Override
public Optional<String> getErrorMessage(Object objectValue, Annotation annotation) {
    if (isCorrect(objectValue, annotation))
        return Optional.absent();

    Size sizeAnnotation = (Size) annotation;

    if (objectValue instanceof String) {
        return Optional.of(createErrorMessageForString(sizeAnnotation));
    } else {
        return Optional.of(createErrorMessageForCollection(sizeAnnotation));
    }
}