Java 类org.springframework.core.GenericTypeResolver 实例源码

项目:lams    文件:GenericTypeAwarePropertyDescriptor.java   
@Override
public synchronized Class<?> getPropertyType() {
    if (this.propertyType == null) {
        if (this.readMethod != null) {
            this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
        }
        else {
            MethodParameter writeMethodParam = getWriteMethodParameter();
            if (writeMethodParam != null) {
                this.propertyType = writeMethodParam.getParameterType();
            }
            else {
                this.propertyType = super.getPropertyType();
            }
        }
    }
    return this.propertyType;
}
项目:lams    文件:FormattingConversionService.java   
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addFormatterForFieldAnnotation(AnnotationFormatterFactory annotationFormatterFactory) {
    final Class<? extends Annotation> annotationType = (Class<? extends Annotation>)
            GenericTypeResolver.resolveTypeArgument(annotationFormatterFactory.getClass(), AnnotationFormatterFactory.class);
    if (annotationType == null) {
        throw new IllegalArgumentException("Unable to extract parameterized Annotation type argument from AnnotationFormatterFactory [" +
                annotationFormatterFactory.getClass().getName() + "]; does the factory parameterize the <A extends Annotation> generic type?");
    }
    if (this.embeddedValueResolver != null && annotationFormatterFactory instanceof EmbeddedValueResolverAware) {
        ((EmbeddedValueResolverAware) annotationFormatterFactory).setEmbeddedValueResolver(this.embeddedValueResolver);
    }
    Set<Class<?>> fieldTypes = annotationFormatterFactory.getFieldTypes();
    for (final Class<?> fieldType : fieldTypes) {
        addConverter(new AnnotationPrinterConverter(annotationType, annotationFormatterFactory, fieldType));
        addConverter(new AnnotationParserConverter(annotationType, annotationFormatterFactory, fieldType));
    }
}
项目:taboola-cronyx    文件:ConfigUtil.java   
public static <T> List<Pair<Class, T>> cronyxQuartzConverterPairs(Class<T> tClass) {

        List<Pair<Class, T>> results = new ArrayList<>();

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(tClass));

        Set<BeanDefinition> components = provider.findCandidateComponents(PACKAGE);
        for (BeanDefinition component : components) {
            try {
                Class cls = Class.forName(component.getBeanClassName());
                Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(cls, tClass);
                results.add(new ImmutablePair<>(typeArgument, (T) cls.newInstance()));

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new CronyxException("Could not instantiate cronyxToQuartzConverters", e);
            }
        }
        return results;
    }
项目:spring4-understanding    文件:HeaderMethodArgumentResolverTests.java   
@Before
public void setup() throws Exception {
    @SuppressWarnings("resource")
    GenericApplicationContext cxt = new GenericApplicationContext();
    cxt.refresh();
    this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory());

    Method method = getClass().getDeclaredMethod("handleMessage",
            String.class, String.class, String.class, String.class, String.class);
    this.paramRequired = new SynthesizingMethodParameter(method, 0);
    this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 1);
    this.paramSystemProperty = new SynthesizingMethodParameter(method, 2);
    this.paramNotAnnotated = new SynthesizingMethodParameter(method, 3);
    this.paramNativeHeader = new SynthesizingMethodParameter(method, 4);

    this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
    GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class);
}
项目:spring4-understanding    文件:AnnotationMethodHandlerExceptionResolver.java   
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
        NativeWebRequest webRequest, Exception thrownException) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Class<?> handlerType = handler.getClass();
    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
        GenericTypeResolver.resolveParameterType(methodParam, handlerType);
        Class<?> paramType = methodParam.getParameterType();
        Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
            args[i] = argValue;
        }
        else {
            throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                    "] for @ExceptionHandler method: " + handlerMethod);
        }
    }
    return args;
}
项目:spring4-understanding    文件:AdviceModeImportSelector.java   
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
    Class<?> annoType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
    if (attributes == null) {
        throw new IllegalArgumentException(String.format(
            "@%s is not present on importing class '%s' as expected",
            annoType.getSimpleName(), importingClassMetadata.getClassName()));
    }

    AdviceMode adviceMode = attributes.getEnum(this.getAdviceModeAttributeName());
    String[] imports = selectImports(adviceMode);
    if (imports == null) {
        throw new IllegalArgumentException(String.format("Unknown AdviceMode: '%s'", adviceMode));
    }
    return imports;
}
项目:spring4-understanding    文件:AnnotationMethodHandlerExceptionResolver.java   
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
        NativeWebRequest webRequest, Exception thrownException) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Class<?> handlerType = handler.getClass();
    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
        GenericTypeResolver.resolveParameterType(methodParam, handlerType);
        Class<?> paramType = methodParam.getParameterType();
        Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
            args[i] = argValue;
        }
        else {
            throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                    "] for @ExceptionHandler method: " + handlerMethod);
        }
    }
    return args;
}
项目:spring4-understanding    文件:FrameworkServlet.java   
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
        String className, ConfigurableApplicationContext wac) {
    try {
        Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
        Class<?> initializerContextClass =
                GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
                    "Could not add context initializer [%s] since its generic parameter [%s] " +
                    "is not assignable from the type of application context used by this " +
                    "framework servlet [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
                    wac.getClass().getName()));
        }
        return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
    }
    catch (Exception ex) {
        throw new IllegalArgumentException(String.format("Could not instantiate class [%s] specified " +
                "via 'contextInitializerClasses' init-param", className), ex);
    }
}
项目:spring4-understanding    文件:ContextLoader.java   
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
            determineContextInitializerClasses(sc);

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass =
                GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
                    "Could not add context initializer [%s] since its generic parameter [%s] " +
                    "is not assignable from the type of application context used by this " +
                    "context loader [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
                    wac.getClass().getName()));
        }
        this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(this.contextInitializers);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
        initializer.initialize(wac);
    }
}
项目:my-spring-cache-redis    文件:FormattingConversionService.java   
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addFormatterForFieldAnnotation(AnnotationFormatterFactory annotationFormatterFactory) {
    final Class<? extends Annotation> annotationType = (Class<? extends Annotation>)
            GenericTypeResolver.resolveTypeArgument(annotationFormatterFactory.getClass(), AnnotationFormatterFactory.class);
    if (annotationType == null) {
        throw new IllegalArgumentException("Unable to extract parameterized Annotation type argument from AnnotationFormatterFactory [" +
                annotationFormatterFactory.getClass().getName() + "]; does the factory parameterize the <A extends Annotation> generic type?");
    }
    if (this.embeddedValueResolver != null && annotationFormatterFactory instanceof EmbeddedValueResolverAware) {
        ((EmbeddedValueResolverAware) annotationFormatterFactory).setEmbeddedValueResolver(this.embeddedValueResolver);
    }
    Set<Class<?>> fieldTypes = annotationFormatterFactory.getFieldTypes();
    for (final Class<?> fieldType : fieldTypes) {
        addConverter(new AnnotationPrinterConverter(annotationType, annotationFormatterFactory, fieldType));
        addConverter(new AnnotationParserConverter(annotationType, annotationFormatterFactory, fieldType));
    }
}
项目:spring    文件:AdviceModeImportSelector.java   
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
    Class<?> annoType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
    if (attributes == null) {
        throw new IllegalArgumentException(String.format(
            "@%s is not present on importing class '%s' as expected",
            annoType.getSimpleName(), importingClassMetadata.getClassName()));
    }

    AdviceMode adviceMode = attributes.getEnum(this.getAdviceModeAttributeName());
    String[] imports = selectImports(adviceMode);
    if (imports == null) {
        throw new IllegalArgumentException(String.format("Unknown AdviceMode: '%s'", adviceMode));
    }
    return imports;
}
项目:dubbox-solr    文件:CustomConversions.java   
private void registerConversion(Object converter) {
    Class<?> type = converter.getClass();
    boolean isWriting = type.isAnnotationPresent(WritingConverter.class);
    boolean isReading = type.isAnnotationPresent(ReadingConverter.class);

    if (!isReading && !isWriting) {
        isReading = true;
        isWriting = true;
    }

    if (converter instanceof GenericConverter) {
        GenericConverter genericConverter = (GenericConverter) converter;
        for (ConvertiblePair pair : genericConverter.getConvertibleTypes()) {
            register(new ConvertibleContext(pair, isReading, isWriting));
        }
    } else if (converter instanceof Converter) {
        Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class);
        register(new ConvertibleContext(arguments[0], arguments[1], isReading, isWriting));
    } else {
        throw new IllegalArgumentException("Unsupported Converter type! Expected either GenericConverter if Converter.");
    }
}
项目:spring-data-crate    文件:CustomConversions.java   
/**
 * Registers a conversion for the given converter. Inspects either generics or the convertible pairs returned
 * by a {@link GenericConverter}.
 *
 * @param converter the converter to register.
 */
private void registerConversion(final Object converter) {
  Class<?> type = converter.getClass();
  boolean isWriting = type.isAnnotationPresent(WritingConverter.class);
  boolean isReading = type.isAnnotationPresent(ReadingConverter.class);

  if (converter instanceof GenericConverter) {
    GenericConverter genericConverter = (GenericConverter) converter;
    for (GenericConverter.ConvertiblePair pair : genericConverter.getConvertibleTypes()) {
      register(new ConverterRegistration(pair, isReading, isWriting));
    }
  } else if (converter instanceof Converter) {
    Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class);
    register(new ConverterRegistration(arguments[0], arguments[1], isReading, isWriting));
  } else {
    throw new IllegalArgumentException("Unsupported Converter type!");
  }
}
项目:spring-envers-audit    文件:RevisionAwareJpaRepositoryFactoryBean.java   
@Override
public <T> T getRepository(Class<T> repositoryInterface, Object customImplementation) {
    if (RevisionRepository.class.isAssignableFrom(repositoryInterface)) {
        Class<?>[] typeArguments = GenericTypeResolver.resolveTypeArguments(repositoryInterface, RevisionRepository.class);
        Class<?> revisionNumberType = typeArguments[2];

        if (!revisionEntityInformation.getRevisionNumberType().equals(revisionNumberType)) {
            throw new IllegalStateException(String.format(
                    "Configured a revision entity type of %s with a revision type of %s "
                            + "but the repository interface is typed to a revision type of %s!", repositoryInterface,
                    revisionEntityInformation.getRevisionNumberType(), revisionNumberType));
        }
    }

    return super.getRepository(repositoryInterface, customImplementation);
}
项目:class-guard    文件:AnnotationMethodHandlerExceptionResolver.java   
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
        NativeWebRequest webRequest, Exception thrownException) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Class<?> handlerType = handler.getClass();
    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new MethodParameter(handlerMethod, i);
        GenericTypeResolver.resolveParameterType(methodParam, handlerType);
        Class<?> paramType = methodParam.getParameterType();
        Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
            args[i] = argValue;
        }
        else {
            throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                    "] for @ExceptionHandler method: " + handlerMethod);
        }
    }
    return args;
}
项目:class-guard    文件:FormattingConversionService.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addFormatterForFieldAnnotation(AnnotationFormatterFactory annotationFormatterFactory) {
    final Class<? extends Annotation> annotationType = (Class<? extends Annotation>)
            GenericTypeResolver.resolveTypeArgument(annotationFormatterFactory.getClass(), AnnotationFormatterFactory.class);
    if (annotationType == null) {
        throw new IllegalArgumentException("Unable to extract parameterized Annotation type argument from AnnotationFormatterFactory [" +
                annotationFormatterFactory.getClass().getName() + "]; does the factory parameterize the <A extends Annotation> generic type?");
    }
    if (this.embeddedValueResolver != null && annotationFormatterFactory instanceof EmbeddedValueResolverAware) {
        ((EmbeddedValueResolverAware) annotationFormatterFactory).setEmbeddedValueResolver(this.embeddedValueResolver);
    }
    Set<Class<?>> fieldTypes = annotationFormatterFactory.getFieldTypes();
    for (final Class<?> fieldType : fieldTypes) {
        addConverter(new AnnotationPrinterConverter(annotationType, annotationFormatterFactory, fieldType));
        addConverter(new AnnotationParserConverter(annotationType, annotationFormatterFactory, fieldType));
    }
}
项目:class-guard    文件:AnnotationMethodHandlerExceptionResolver.java   
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
        NativeWebRequest webRequest, Exception thrownException) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Class<?> handlerType = handler.getClass();
    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new MethodParameter(handlerMethod, i);
        GenericTypeResolver.resolveParameterType(methodParam, handlerType);
        Class<?> paramType = methodParam.getParameterType();
        Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
            args[i] = argValue;
        }
        else {
            throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                    "] for @ExceptionHandler method: " + handlerMethod);
        }
    }
    return args;
}
项目:class-guard    文件:FrameworkServlet.java   
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
        String className, ConfigurableApplicationContext wac) {
    try {
        Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
        Class<?> initializerContextClass =
                GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
                    "Could not add context initializer [%s] since its generic parameter [%s] " +
                    "is not assignable from the type of application context used by this " +
                    "framework servlet [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
                    wac.getClass().getName()));
        }
        return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
    }
    catch (Exception ex) {
        throw new IllegalArgumentException(String.format("Could not instantiate class [%s] specified " +
                "via 'contextInitializerClasses' init-param", className), ex);
    }
}
项目:class-guard    文件:GenericTypeAwarePropertyDescriptor.java   
@Override
public synchronized Class<?> getPropertyType() {
    if (this.propertyType == null) {
        if (this.readMethod != null) {
            this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
        }
        else {
            MethodParameter writeMethodParam = getWriteMethodParameter();
            if (writeMethodParam != null) {
                this.propertyType = writeMethodParam.getParameterType();
            }
            else {
                this.propertyType = super.getPropertyType();
            }
        }
    }
    return this.propertyType;
}
项目:spring-data-solr    文件:CustomConversions.java   
private void registerConversion(Object converter) {
    Class<?> type = converter.getClass();
    boolean isWriting = type.isAnnotationPresent(WritingConverter.class);
    boolean isReading = type.isAnnotationPresent(ReadingConverter.class);

    if (!isReading && !isWriting) {
        isReading = true;
        isWriting = true;
    }

    if (converter instanceof GenericConverter) {
        GenericConverter genericConverter = (GenericConverter) converter;
        for (ConvertiblePair pair : genericConverter.getConvertibleTypes()) {
            register(new ConvertibleContext(pair, isReading, isWriting));
        }
    } else if (converter instanceof Converter) {
        Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class);
        register(new ConvertibleContext(arguments[0], arguments[1], isReading, isWriting));
    } else {
        throw new IllegalArgumentException("Unsupported Converter type! Expected either GenericConverter if Converter.");
    }
}
项目:screensaver    文件:AbstractEntityInstanceTest.java   
@Override
public synchronized Class<?> getPropertyType() {
    if (this.propertyType == null) {
        if (this.readMethod != null) {
            this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
        }
        else {
            MethodParameter writeMethodParam = getWriteMethodParameter();
            if (writeMethodParam != null) {
                this.propertyType = writeMethodParam.getParameterType();
            }
            else {
                this.propertyType = super.getPropertyType();
            }
        }
    }
    return this.propertyType;
}
项目:spring-data-jdbc    文件:BaseJdbcRepository.java   
@SuppressWarnings("unchecked")
private EntityInformation<T, ID> createEntityInformation() {

    Class<T> entityType = (Class<T>) GenericTypeResolver.resolveTypeArguments(getClass(),
                                                                              JdbcRepository.class)[0];

    return createEntityInformation(entityType);
}
项目:jigsaw-payment    文件:TProtobufProcessor.java   
private Class<?> getParameterizedType(Object target) throws TException {
    Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(
            target.getClass(), Controller.class);
    if (arguments.length != 2)
        throw new TException(
                "Error to resolve request type, please make sure "
                        + target.getClass()
                        + " has provided type arguments for Controller class.");
    return arguments[0];
}
项目:gemini.blueprint    文件:ListListenerAdapter.java   
@SuppressWarnings("rawtypes")
   public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
    Object[] listeners = tracker.getServices();

    if (listeners != null) {
        synchronized (eventCache) {
            for (Object listnr : listeners) {
                   OsgiBundleApplicationContextListener listener = (OsgiBundleApplicationContextListener) listnr;
                Class<? extends OsgiBundleApplicationContextListener> listenerClass = listener.getClass();
                Class<? extends OsgiBundleApplicationContextEvent> eventType = eventCache.get(listenerClass);
                if (eventType == null) {
                    Class<?> evtType =
                            GenericTypeResolver.resolveTypeArgument(listenerClass,
                                    OsgiBundleApplicationContextListener.class);
                    if (evtType == null) {
                        evtType = OsgiBundleApplicationContextEvent.class;
                    }
                    if (evtType != null && OsgiBundleApplicationContextEvent.class.isAssignableFrom(evtType)) {
                        eventType = (Class<? extends OsgiBundleApplicationContextEvent>) evtType;
                    } else {
                        eventType = OsgiBundleApplicationContextEvent.class;
                    }
                    eventCache.put(listenerClass, eventType);
                }
                if (eventType.isInstance(event)) {
                    listener.onOsgiApplicationEvent(event);
                }
            }
        }
    }
}
项目:gemini.blueprint    文件:ApplicationListenerAdapter.java   
private ApplicationListenerAdapter(OsgiBundleApplicationContextListener<E> listener) {
    this.osgiListener = listener;
    Class<?> evtType =
            GenericTypeResolver
                    .resolveTypeArgument(listener.getClass(), OsgiBundleApplicationContextListener.class);
    this.eventType = (evtType == null ? OsgiBundleApplicationContextEvent.class : evtType);

    toString = "ApplicationListenerAdapter for listener " + osgiListener;
}
项目:lams    文件:ContextLoader.java   
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #createWebApplicationContext(ServletContext, ApplicationContext)
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
            determineContextInitializerClasses(sc);
    if (initializerClasses.isEmpty()) {
        // no ApplicationContextInitializers have been declared -> nothing to do
        return;
    }

    ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances =
            new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass =
                GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
                    "Could not add context initializer [%s] since its generic parameter [%s] " +
                    "is not assignable from the type of application context used by this " +
                    "context loader [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
                    wac.getClass().getName()));
        }
        initializerInstances.add(BeanUtils.instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(initializerInstances);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
        initializer.initialize(wac);
    }
}
项目:lams    文件:InvocableHandlerMethod.java   
/**
 * Get the method argument values for the current request.
 */
private Object[] getMethodArgumentValues(NativeWebRequest request, ModelAndViewContainer mavContainer,
        Object... providedArgs) throws Exception {

    MethodParameter[] parameters = getMethodParameters();
    Object[] args = new Object[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        MethodParameter parameter = parameters[i];
        parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());
        args[i] = resolveProvidedArgument(parameter, providedArgs);
        if (args[i] != null) {
            continue;
        }
        if (this.argumentResolvers.supportsParameter(parameter)) {
            try {
                args[i] = this.argumentResolvers.resolveArgument(
                        parameter, mavContainer, request, this.dataBinderFactory);
                continue;
            }
            catch (Exception ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace(getArgumentResolutionErrorMessage("Error resolving argument", i), ex);
                }
                throw ex;
            }
        }
        if (args[i] == null) {
            String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i);
            throw new IllegalStateException(msg);
        }
    }
    return args;
}
项目:lams    文件:HandlerMethodInvoker.java   
protected final void addReturnValueAsModelAttribute(Method handlerMethod, Class<?> handlerType,
        Object returnValue, ExtendedModelMap implicitModel) {

    ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class);
    String attrName = (attr != null ? attr.value() : "");
    if ("".equals(attrName)) {
        Class<?> resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType);
        attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue);
    }
    implicitModel.addAttribute(attrName, returnValue);
}
项目:lams    文件:AdviceModeImportSelector.java   
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
    Class<?> annoType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
    Assert.notNull(attributes, String.format(
            "@%s is not present on importing class '%s' as expected",
            annoType.getSimpleName(), importingClassMetadata.getClassName()));

    AdviceMode adviceMode = attributes.getEnum(this.getAdviceModeAttributeName());
    String[] imports = selectImports(adviceMode);
    Assert.notNull(imports, String.format("Unknown AdviceMode: '%s'", adviceMode));
    return imports;
}
项目:lams    文件:GenericTypeAwarePropertyDescriptor.java   
public synchronized MethodParameter getWriteMethodParameter() {
    if (this.writeMethod == null) {
        return null;
    }
    if (this.writeMethodParameter == null) {
        this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
        GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
    }
    return this.writeMethodParameter;
}
项目:lams    文件:ConstructorResolver.java   
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
        String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

    Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
            ((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
    TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
            this.beanFactory.getCustomTypeConverter() : bw);
    BeanDefinitionValueResolver valueResolver =
            new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
        GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
        if (argValue instanceof AutowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
        }
        else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        }
        else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Class<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        }
        catch (TypeMismatchException ex) {
            String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
            throw new UnsatisfiedDependencyException(
                    mbd.getResourceDescription(), beanName, argIndex, paramType,
                    "Could not convert " + methodType + " argument value of type [" +
                    ObjectUtils.nullSafeClassName(argValue) +
                    "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}
项目:lams    文件:DependencyDescriptor.java   
/**
 * Optionally set the concrete class that contains this dependency.
 * This may differ from the class that declares the parameter/field in that
 * it may be a subclass thereof, potentially substituting type variables.
 */
public void setContainingClass(Class<?> containingClass) {
    this.containingClass = containingClass;
    if (this.methodParameter != null) {
        GenericTypeResolver.resolveParameterType(this.methodParameter, containingClass);
    }
}
项目:lams    文件:FormattingConversionService.java   
@Override
public void addFormatter(Formatter<?> formatter) {
    Class<?> fieldType = GenericTypeResolver.resolveTypeArgument(formatter.getClass(), Formatter.class);
    if (fieldType == null) {
        throw new IllegalArgumentException("Unable to extract parameterized field type argument from Formatter [" +
                formatter.getClass().getName() + "]; does the formatter parameterize the <T> generic type?");
    }
    addFormatterForFieldType(fieldType, formatter);
}
项目:hibernate-springcache    文件:SpringCacheToJCache.java   
@SuppressWarnings("unchecked")
public SpringCacheToJCache(final CacheManager cacheManager, final org.springframework.cache.Cache springCache) {
    super();
final Class<?>[] genericArguments = GenericTypeResolver.resolveTypeArguments(
    getClass(), SpringCacheToJCache.class );
this.cacheManager = cacheManager;
this.valueClass = (Class<V>) (genericArguments == null ? Object.class : genericArguments[1]);
    this.springCache = springCache;
}
项目:alfresco-remote-api    文件:ResourceInspectorUtil.java   
/**
 * Determine the expected type as the returned type of the method.
 * If the return type is a List it will return the generic element type instead of a List.
 * @param resource - resource with methods
 * @param method Method
 * @return Class - type of class it needs.
 */
@SuppressWarnings("rawtypes")
protected static Class determineType(Class resource, Method method)
{
    Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);

    /*
    * The api is consistent that the object passed in must match the object passed out
    * however, operations are different, if the param is supplied  it doesn't have to match
    * the return type.
    * So we need special logic for operations
     */
    Annotation annot = AnnotationUtils.findAnnotation(resolvedMethod, Operation.class);
    if (annot != null)
    {
        return determineOperationType(resource, method);
    }
    else
    {
        Class returnType = GenericTypeResolver.resolveReturnType(resolvedMethod, resource);
        if (List.class.isAssignableFrom(returnType))
        {
            return GenericCollectionTypeResolver.getCollectionReturnType(method);
        }
        return returnType;
    }
}
项目:FastDFS_Client    文件:FdfsResponse.java   
/**
 * 构造函数
 * 
 * @param genericType
 */
@SuppressWarnings("unchecked")
public FdfsResponse() {
    super();
    this.genericType = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), FdfsResponse.class);
    // Type theclass = this.getClass().getGenericSuperclass();
    // this.genericType = ((ParameterizedType)
    // theclass).getActualTypeArguments()[0];
}
项目:redjob    文件:ExecutionModule.java   
/**
 * Extract type from serializer and register it.
 */
@SuppressWarnings("unchecked")
protected <T> void addTypedSerializer(JsonSerializer<T> serializer) {
   addSerializer(
         (Class<? extends T>) GenericTypeResolver.resolveTypeArgument(serializer.getClass(), JsonSerializer.class),
         serializer);
}
项目:redjob    文件:ExecutionModule.java   
/**
 * Extract type from deserializer and register it.
 */
@SuppressWarnings("unchecked")
protected <T> void addTypedDeserializer(JsonDeserializer<? extends T> deserializer) {
   addDeserializer(
         (Class<T>) GenericTypeResolver.resolveTypeArgument(deserializer.getClass(), JsonDeserializer.class),
         deserializer);
}
项目:spring4-understanding    文件:InvocableHandlerMethod.java   
/**
 * Get the method argument values for the current request.
 */
private Object[] getMethodArgumentValues(Message<?> message, Object... providedArgs) throws Exception {
    MethodParameter[] parameters = getMethodParameters();
    Object[] args = new Object[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        MethodParameter parameter = parameters[i];
        parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());
        args[i] = resolveProvidedArgument(parameter, providedArgs);
        if (args[i] != null) {
            continue;
        }
        if (this.argumentResolvers.supportsParameter(parameter)) {
            try {
                args[i] = this.argumentResolvers.resolveArgument(parameter, message);
                continue;
            }
            catch (Exception ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug(getArgumentResolutionErrorMessage("Error resolving argument", i), ex);
                }
                throw ex;
            }
        }
        if (args[i] == null) {
            String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i);
            throw new IllegalStateException(msg);
        }
    }
    return args;
}
项目:spring4-understanding    文件:DestinationVariableMethodArgumentResolverTests.java   
@Before
public void setup() throws Exception {
    this.resolver = new DestinationVariableMethodArgumentResolver(new DefaultConversionService());

    Method method = getClass().getDeclaredMethod("handleMessage", String.class, String.class, String.class);
    this.paramAnnotated = new MethodParameter(method, 0);
    this.paramAnnotatedValue = new MethodParameter(method, 1);
    this.paramNotAnnotated = new MethodParameter(method, 2);

    this.paramAnnotated.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
    GenericTypeResolver.resolveParameterType(this.paramAnnotated, DestinationVariableMethodArgumentResolver.class);
    this.paramAnnotatedValue.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
    GenericTypeResolver.resolveParameterType(this.paramAnnotatedValue, DestinationVariableMethodArgumentResolver.class);
}