All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.coditory.quark.context.ConstructorBasedBeanCreator Maven / Gradle / Ivy

There is a newer version: 0.1.22
Show newest version
package com.coditory.quark.context;

import com.coditory.quark.context.annotations.ConditionalOnBean;
import com.coditory.quark.context.annotations.Inject;

import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;

import static com.coditory.quark.context.DependencyResolver.resolveArguments;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

final class ConstructorBasedBeanCreator implements BeanCreator {
    @SuppressWarnings("unchecked")
    static  ConstructorBasedBeanCreator fromConstructor(Class type) {
        Constructor[] constructors = type.getConstructors();
        Constructor constructor;
        if (constructors.length == 1) {
            constructor = (Constructor) constructors[0];
        } else {
            List> annotated = Arrays.stream(constructors)
                    .filter(c -> c.isAnnotationPresent(Inject.class))
                    .map(c -> (Constructor) c)
                    .collect(toList());
            if (annotated.size() == 1) {
                constructor = annotated.get(0);
            } else if (annotated.size() > 1) {
                throw new ContextException("Expected single constructor annotated with @Inject in class: "
                        + type.getCanonicalName() + ". Got: " + annotated.size());
            } else {
                throw new ContextException("Located multiple constructors in a bean of type: "
                        + type.getCanonicalName() + ". Mark one with @Inject.");
            }
        }
        constructor.setAccessible(true);
        return new ConstructorBasedBeanCreator<>(type, constructor);
    }

    private final Class type;
    private final Constructor constructor;

    ConstructorBasedBeanCreator(Class type, Constructor constructor) {
        this.type = requireNonNull(type);
        this.constructor = requireNonNull(constructor);
    }

    @Override
    public T create(ResolutionContext context) {
        Object[] args = resolveArguments(constructor, context);
        try {
            return constructor.newInstance(args);
        } catch (Exception e) {
            throw new ContextException("Could no create bean from constructor: " + constructor, e);
        }
    }

    @Override
    public boolean isActive(ConditionContext context) {
        return ConditionsResolver.isActive(context, type);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy