Search in sources :

Example 1 with InstantiationException

use of io.micronaut.core.reflect.exception.InstantiationException in project micronaut-core by micronaut-projects.

the class InstantiationUtils method tryInstantiate.

/**
 * Try to instantiate the given class using {@link io.micronaut.core.beans.BeanIntrospector}.
 *
 * @param type The type
 * @param propertiesMap The properties values {@link Map} of the instance
 * @param context The Conversion context
 * @param <T> The generic type
 * @return The instantiated instance or {@link Optional#empty()}
 * @throws InstantiationException When an error occurs
 */
@NonNull
public static <T> Optional<T> tryInstantiate(@NonNull Class<T> type, Map propertiesMap, ConversionContext context) {
    ArgumentUtils.requireNonNull("type", type);
    if (propertiesMap.isEmpty()) {
        return tryInstantiate(type);
    }
    final Supplier<T> reflectionFallback = () -> {
        Logger log = LoggerFactory.getLogger(InstantiationUtils.class);
        if (log.isDebugEnabled()) {
            log.debug("Tried, but could not instantiate type: " + type);
        }
        return null;
    };
    T result = BeanIntrospector.SHARED.findIntrospection(type).map(introspection -> {
        T instance;
        Argument[] constructorArguments = introspection.getConstructorArguments();
        List<Object> arguments = new ArrayList<>(constructorArguments.length);
        try {
            if (constructorArguments.length > 0) {
                Map bindMap = new LinkedHashMap(propertiesMap.size());
                Set<Map.Entry<?, ?>> entries = propertiesMap.entrySet();
                for (Map.Entry<?, ?> entry : entries) {
                    Object key = entry.getKey();
                    bindMap.put(NameUtils.decapitalize(NameUtils.dehyphenate(key.toString())), entry.getValue());
                }
                for (Argument<?> argument : constructorArguments) {
                    if (bindMap.containsKey(argument.getName())) {
                        Object converted = ConversionService.SHARED.convert(bindMap.get(argument.getName()), argument.getType(), ConversionContext.of(argument)).orElseThrow(() -> new ConversionErrorException(argument, context.getLastError().orElse(() -> new IllegalArgumentException("Value [" + bindMap.get(argument.getName()) + "] cannot be converted to type : " + argument.getType()))));
                        arguments.add(converted);
                    } else if (argument.isDeclaredNullable()) {
                        arguments.add(null);
                    } else {
                        context.reject(new ConversionErrorException(argument, () -> new IllegalArgumentException("No Value found for argument " + argument.getName())));
                    }
                }
                instance = introspection.instantiate(arguments.toArray());
            } else {
                instance = introspection.instantiate();
            }
            return instance;
        } catch (InstantiationException e) {
            return reflectionFallback.get();
        }
    }).orElseGet(reflectionFallback);
    return Optional.ofNullable(result);
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) Supplier(java.util.function.Supplier) NonNull(io.micronaut.core.annotation.NonNull) ConversionContext(io.micronaut.core.convert.ConversionContext) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) Argument(io.micronaut.core.type.Argument) NameUtils(io.micronaut.core.naming.NameUtils) BeanIntrospector(io.micronaut.core.beans.BeanIntrospector) ConversionService(io.micronaut.core.convert.ConversionService) InstantiationException(io.micronaut.core.reflect.exception.InstantiationException) Argument(io.micronaut.core.type.Argument) Logger(org.slf4j.Logger) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) InstantiationException(io.micronaut.core.reflect.exception.InstantiationException) NonNull(io.micronaut.core.annotation.NonNull)

Example 2 with InstantiationException

use of io.micronaut.core.reflect.exception.InstantiationException in project micronaut-core by micronaut-projects.

the class InstantiationUtils method instantiate.

/**
 * Instantiate the given class rethrowing any exceptions as {@link InstantiationException}.
 *
 * @param type     The type
 * @param argTypes The argument types
 * @param args     The values of arguments
 * @param <T>      The generic type
 * @return The instantiated instance
 * @throws InstantiationException When an error occurs
 * @since 3.0.0
 */
public static <T> T instantiate(Class<T> type, Class<?>[] argTypes, Object... args) {
    try {
        return BeanIntrospector.SHARED.findIntrospection(type).map(bi -> bi.instantiate(args)).orElseGet(() -> {
            try {
                Logger log = ClassUtils.REFLECTION_LOGGER;
                if (log.isDebugEnabled()) {
                    log.debug("Reflectively instantiating type: " + type);
                }
                final Constructor<T> declaredConstructor = type.getDeclaredConstructor(argTypes);
                declaredConstructor.setAccessible(true);
                return declaredConstructor.newInstance(args);
            } catch (Throwable e) {
                throw new InstantiationException("Could not instantiate type [" + type.getName() + "]: " + e.getMessage(), e);
            }
        });
    } catch (Throwable e) {
        throw new InstantiationException("Could not instantiate type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) Supplier(java.util.function.Supplier) NonNull(io.micronaut.core.annotation.NonNull) ConversionContext(io.micronaut.core.convert.ConversionContext) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) Argument(io.micronaut.core.type.Argument) NameUtils(io.micronaut.core.naming.NameUtils) BeanIntrospector(io.micronaut.core.beans.BeanIntrospector) ConversionService(io.micronaut.core.convert.ConversionService) InstantiationException(io.micronaut.core.reflect.exception.InstantiationException) Logger(org.slf4j.Logger) InstantiationException(io.micronaut.core.reflect.exception.InstantiationException)

Aggregations

NonNull (io.micronaut.core.annotation.NonNull)2 BeanIntrospection (io.micronaut.core.beans.BeanIntrospection)2 BeanIntrospector (io.micronaut.core.beans.BeanIntrospector)2 ConversionContext (io.micronaut.core.convert.ConversionContext)2 ConversionService (io.micronaut.core.convert.ConversionService)2 ConversionErrorException (io.micronaut.core.convert.exceptions.ConversionErrorException)2 NameUtils (io.micronaut.core.naming.NameUtils)2 InstantiationException (io.micronaut.core.reflect.exception.InstantiationException)2 Argument (io.micronaut.core.type.Argument)2 ArgumentUtils (io.micronaut.core.util.ArgumentUtils)2 Constructor (java.lang.reflect.Constructor)2 java.util (java.util)2 Function (java.util.function.Function)2 Supplier (java.util.function.Supplier)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2