Java源码示例:ru.vyarus.java.generics.resolver.GenericsResolver

示例1
/**
 * Analyze configuration object to extract bindable parts.
 *
 * @param bootstrap     bootstrap instance
 * @param configuration configuration instance
 * @param introspect    true to introspect configuration object and extract values by path and unique
 *                      sub configurations
 * @return parsed configuration info
 */
public static ConfigurationTree build(final Bootstrap bootstrap,
                                      final Configuration configuration,
                                      final boolean introspect) {
    final List<Class> roots = resolveRootTypes(new ArrayList<>(), configuration.getClass());
    if (introspect) {
        final List<ConfigPath> content = resolvePaths(
                bootstrap.getObjectMapper().getSerializationConfig(),
                null,
                new ArrayList<>(),
                configuration.getClass(),
                configuration,
                GenericsResolver.resolve(configuration.getClass()));
        final List<ConfigPath> uniqueContent = resolveUniqueTypePaths(content);
        return new ConfigurationTree(roots, content, uniqueContent);
    } else {
        return new ConfigurationTree(roots);
    }
}
 
示例2
@Override
public void install(final AbstractBinder binder, final Injector injector, final Class<Object> type) {
    final boolean hkExtension = isJerseyExtension(type);
    final boolean forceSingleton = isForceSingleton(type, hkExtension);
    // since jersey 2.26 internal hk Factory class replaced by java 8 Supplier
    if (is(type, Supplier.class)) {
        // register factory directly (without wrapping)
        bindFactory(binder, injector, type, hkExtension, forceSingleton);

    } else {
        // support multiple extension interfaces on one type
        final Set<Class<?>> extensions = Sets.intersection(EXTENSION_TYPES,
                GenericsResolver.resolve(type).getGenericsInfo().getComposingTypes());
        if (!extensions.isEmpty()) {
            for (Class<?> ext : extensions) {
                bindSpecificComponent(binder, injector, type, ext, hkExtension, forceSingleton);
            }
        } else {
            // no known extension found
            bindComponent(binder, injector, type, hkExtension, forceSingleton);
        }
    }
}
 
示例3
/**
 * Binds jersey {@link Supplier}. If bean is {@link JerseyManaged} then registered directly as
 * factory. Otherwise register factory through special "lazy bridge" to delay guice factory bean instantiation.
 * Also registers factory directly (through wrapper to be able to inject factory by its type).
 * <p>
 * NOTE: since jersey 2.26 jersey don't use hk2 directly and so all HK interfaces replaced by java 8 interfaces.
 *
 * @param binder        jersey binder
 * @param injector      guice injector
 * @param type          factory to bind
 * @param jerseyManaged true if bean must be managed by jersey, false to bind guice managed instance
 * @param singleton     true to force singleton scope
 * @param <T>           actual type (used to workaround type checks)
 * @see ru.vyarus.dropwizard.guice.module.jersey.support.LazyGuiceFactory
 * @see ru.vyarus.dropwizard.guice.module.jersey.support.GuiceComponentFactory
 */
@SuppressWarnings("unchecked")
public static <T> void bindFactory(final AbstractBinder binder, final Injector injector, final Class<?> type,
                                   final boolean jerseyManaged, final boolean singleton) {
    // resolve Factory<T> actual type to bind properly
    final Class<T> res = (Class<T>) GenericsResolver.resolve(type).type(Supplier.class).generic(0);
    if (jerseyManaged) {
        optionalSingleton(singleton
                        ? binder.bindFactory((Class<Supplier<T>>) type, Singleton.class).to(type).to(res)
                        : binder.bindFactory((Class<Supplier<T>>) type).to(type).to(res),
                singleton);
    } else {
        binder.bindFactory(new LazyGuiceFactory(injector, type)).to(res);
        // binding factory type to be able to autowire factory by name
        optionalSingleton(binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type),
                singleton);
    }
}
 
示例4
/**
 * Binds jersey specific component (component implements jersey interface or extends class).
 * Specific binding is required for types directly supported by jersey (e.g. ExceptionMapper).
 * Such types must be bound to target interface directly, otherwise jersey would not be able to resolve them.
 * <p> If type is {@link JerseyManaged}, binds directly.
 * Otherwise, use guice "bridge" factory to lazily bind type.</p>
 *
 * @param binder        jersey binder
 * @param injector      guice injector
 * @param type          type which implements specific jersey interface or extends class
 * @param specificType  specific jersey type (interface or abstract class)
 * @param jerseyManaged true if bean must be managed by jersey, false to bind guice managed instance
 * @param singleton     true to force singleton scope
 */
public static void bindSpecificComponent(final AbstractBinder binder,
                                         final Injector injector,
                                         final Class<?> type,
                                         final Class<?> specificType,
                                         final boolean jerseyManaged,
                                         final boolean singleton) {
    // resolve generics of specific type
    final GenericsContext context = GenericsResolver.resolve(type).type(specificType);
    final List<Type> genericTypes = context.genericTypes();
    final Type[] generics = genericTypes.toArray(new Type[0]);
    final Type bindingType = generics.length > 0 ? new ParameterizedTypeImpl(specificType, generics)
            : specificType;
    if (jerseyManaged) {
        optionalSingleton(
                binder.bind(type).to(type).to(bindingType),
                singleton);
    } else {
        optionalSingleton(
                binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type).to(bindingType),
                singleton);
    }
}
 
示例5
/**
 * Analyze target bean methods, finding all matching (by parameters) methods.
 * If method name was specified, only methods with the same name resolved.
 *
 * @param target target bean type
 * @param params repository method params
 * @param hint   method name hint (may be null)
 * @return descriptor of all matching methods
 */
private static List<MatchedMethod> findPossibleMethods(final List<Class<?>> params, final Class<?> target,
                                                       final String hint) {
    final List<MatchedMethod> possibilities = Lists.newArrayList();
    // use generics to enforce type checks
    final GenericsContext targetGenerics = GenericsResolver.resolve(target);
    for (Method method : target.getMethods()) {
        // method hint force to check only methods with this name
        final boolean methodHintValid = hint == null || method.getName().equals(hint);
        if (!isAcceptableMethod(method) || !methodHintValid) {
            continue;
        }
        final MatchedMethod matched = analyzeMethod(method, params, targetGenerics);
        if (matched != null) {
            possibilities.add(matched);
        }
    }
    return possibilities;
}
 
示例6
/**
 * Checks resolved amend extensions compatibility with method specific extension type.
 * Extension may be universal and support some methods and doesn't support other.
 *
 * @param extensions     extensions to check
 * @param descriptorType repository method descriptor type
 * @return filtered extensions list (safe to use by method extension)
 */
public static List<AmendExecutionExtension> filterCompatibleExtensions(
        final List<AmendExecutionExtension> extensions,
        final Class<? extends RepositoryMethodDescriptor> descriptorType) {
    @SuppressWarnings("unchecked")
    final Class<? extends AmendExecutionExtension> supportedExtension =
            (Class<? extends AmendExecutionExtension>) GenericsResolver.resolve(descriptorType)
                    .type(RepositoryMethodDescriptor.class).generic("E");
    return Lists.newArrayList(Iterables.filter(extensions, new Predicate<AmendExecutionExtension>() {
        @Override
        public boolean apply(@Nonnull final AmendExecutionExtension ext) {
            final Class<?> rawExtType = RepositoryUtils.resolveRepositoryClass(ext);
            final boolean compatible = supportedExtension.isAssignableFrom(rawExtType);
            if (!compatible) {
                LOGGER.debug("Extension {} ignored, because it doesn't implement required extension "
                        + "interface {}", rawExtType.getSimpleName(), supportedExtension.getSimpleName());
            }
            return compatible;
        }
    }));
}
 
示例7
public FuzzStatement(FrameworkMethod method, TestClass testClass,
                     GeneratorRepository generatorRepository) {
    this.method = method;
    this.testClass = testClass;
    this.typeVariables =
            GenericsResolver.resolve(testClass.getJavaClass())
                    .method(method.getMethod())
                    .genericsMap();
    this.generatorRepository = generatorRepository;
    this.expectedExceptions = Arrays.asList(method.getMethod().getExceptionTypes());

}
 
示例8
private void processParameters(final DelegateMethodDescriptor descriptor, final DescriptorContext context) {
    final DescriptorContext targetContext = new DescriptorContext();
    targetContext.type = descriptor.target;
    targetContext.method = descriptor.method;
    targetContext.generics = GenericsResolver.resolve(targetContext.type)
            .type(descriptor.method.getDeclaringClass());
    targetContext.extensionAnnotation = context.extensionAnnotation;
    targetContext.extensionType = context.extensionType;
    final DelegateParamsContext paramContext = new DelegateParamsContext(targetContext, context);
    spiService.process(descriptor, paramContext);
}
 
示例9
/**
 * Resolve target conversion type either from listener instance or, if its not possible, from
 * listener parameter declaration.
 *
 * @param listenerType       listener instance type
 * @param declaredTargetType listener generic declared in method declaration
 * @return target conversion type or null if conversion is not required
 */
private Class<?> resolveTargetType(final Class<?> listenerType, final Class<?> declaredTargetType) {
    Class<?> target = null;
    if (RequiresRecordConversion.class.isAssignableFrom(listenerType)) {
        target = GenericsResolver.resolve(listenerType)
                .type(RequiresRecordConversion.class).generic("T");

        // if generic could not be resolved from listener instance, use method parameter declaration (last resort)
        if (Object.class.equals(target)) {
            target = declaredTargetType;
        }
    }
    return target;
}
 
示例10
private DescriptorContext buildDescriptorContext(final Method method, final Class<?> type) {
    final DescriptorContext context = new DescriptorContext();
    context.type = type;
    context.method = method;
    context.generics = GenericsResolver.resolve(type).type(method.getDeclaringClass());
    return context;
}
 
示例11
private static Type[] alignParametrizationArguments(final Class<?> exactActualType,
                                                    final Class<?> knownGenericType,
                                                    final ParameterizedType knownGeneric,
                                                    final LinkedHashMap<String, Type> knownGenerics) {

    final Type[] knownArguments;

    // if base types are equal we can match types in parametrization
    if (exactActualType.equals(knownGenericType)) {
        knownArguments = knownGeneric.getActualTypeArguments();
    } else {
        // known generic type is a subclass of resolved root type.. inception!
        // trying to track generics
        if (knownGenericType.isAssignableFrom(exactActualType)) {
            // Actual type is higher then declared in generic: need to analyze this mismatch
            // (again not known root generics and known generics in sub type)
            final LinkedHashMap<String, Type> sub = track(exactActualType, knownGenericType,
                    GenericsResolutionUtils.resolveGenerics(knownGeneric, knownGenerics));
            knownArguments = sub.values().toArray(new Type[0]);
        } else {
            // actual class, resolved in root class hierarchy is a subtype of known generic type
            // building hierarchy for known generic value class and look generics of required subclass
            final GenericsContext ctx = GenericsResolver.resolve(knownGenericType);
            knownArguments = GenericInfoUtils.create(ctx, knownGeneric)
                    .getTypeGenerics(exactActualType).values().toArray(new Type[0]);
        }
    }
    return knownArguments;
}
 
示例12
/**
 * General convention: extensions declare descriptor with generic T.
 *
 * @param extensionClass extension class
 * @param extensionType  extension type (interface to resolve generic on)
 * @param descriptorType repository method descriptor type
 * @return true if extension is compatible with descriptor, false otherwise
 */
public static boolean isCompatible(final Class<?> extensionClass, final Class<?> extensionType,
                                   final Class<? extends RepositoryMethodDescriptor> descriptorType) {
    final Class<?> compatibleDescriptor = GenericsResolver.resolve(extensionClass)
            .type(extensionType).generic("T");
    return compatibleDescriptor.isAssignableFrom(descriptorType);
}