Search in sources :

Example 1 with Inject

use of org.apache.cayenne.di.Inject in project cayenne by apache.

the class ConstructorInjectingProvider method initConstructor.

@SuppressWarnings("unchecked")
private void initConstructor(Class<? extends T> implementation) {
    Constructor<?>[] constructors = implementation.getDeclaredConstructors();
    Constructor<?> lastMatch = null;
    int lastSize = -1;
    // if multiple matches are found
    for (Constructor<?> constructor : constructors) {
        int size = constructor.getParameterTypes().length;
        if (size <= lastSize) {
            continue;
        }
        if (size == 0) {
            lastSize = 0;
            lastMatch = constructor;
            continue;
        }
        boolean injectable = true;
        for (Annotation[] annotations : constructor.getParameterAnnotations()) {
            boolean parameterInjectable = false;
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().equals(Inject.class)) {
                    parameterInjectable = true;
                    break;
                }
            }
            if (!parameterInjectable) {
                injectable = false;
                break;
            }
        }
        if (injectable) {
            lastSize = size;
            lastMatch = constructor;
        }
    }
    if (lastMatch == null) {
        throw new DIRuntimeException("No applicable constructor is found for constructor injection in class '%s'", implementation.getName());
    }
    // the cast is lame, but Class.getDeclaredConstructors() is not using
    // generics in Java 5 and using <?> in Java 6, creating compilation problems.
    this.constructor = (Constructor<? extends T>) lastMatch;
    Annotation[][] annotations = lastMatch.getParameterAnnotations();
    this.bindingNames = new String[annotations.length];
    for (int i = 0; i < annotations.length; i++) {
        Annotation[] parameterAnnotations = annotations[i];
        for (int j = 0; j < parameterAnnotations.length; j++) {
            Annotation annotation = parameterAnnotations[j];
            if (annotation.annotationType().equals(Inject.class)) {
                Inject inject = (Inject) annotation;
                bindingNames[i] = inject.value();
                break;
            }
        }
    }
}
Also used : Inject(org.apache.cayenne.di.Inject) Constructor(java.lang.reflect.Constructor) DIRuntimeException(org.apache.cayenne.di.DIRuntimeException) Annotation(java.lang.annotation.Annotation)

Aggregations

Annotation (java.lang.annotation.Annotation)1 Constructor (java.lang.reflect.Constructor)1 DIRuntimeException (org.apache.cayenne.di.DIRuntimeException)1 Inject (org.apache.cayenne.di.Inject)1