Search in sources :

Example 1 with Inject

use of javax.inject.Inject in project rest.li by linkedin.

the class Jsr330Adapter method scanInjectableFields.

private void scanInjectableFields(Class<?> beanClazz) {
    InjectableFields fieldDecls = new InjectableFields();
    List<Field> fieldsToScan = new ArrayList<Field>(Arrays.asList(beanClazz.getDeclaredFields()));
    Class<?> superclazz = beanClazz.getSuperclass();
    while (superclazz != Object.class) {
        fieldsToScan.addAll(Arrays.asList(superclazz.getDeclaredFields()));
        superclazz = superclazz.getSuperclass();
    }
    for (Field field : fieldsToScan) {
        log.debug("  Scanning field " + field.getName());
        if (field.getAnnotations().length > 0) {
            // prefer more specific Named fields
            Named namedAnno = field.getAnnotation(Named.class);
            if (namedAnno != null) {
                log.debug("    Using @Named: " + namedAnno.value());
                fieldDecls.add(field, field.getType(), namedAnno.value());
            } else {
                log.debug("    Using @Inject");
                Inject injectAnno = field.getAnnotation(Inject.class);
                if (injectAnno != null) {
                    fieldDecls.add(field, field.getType(), null);
                }
            }
        }
    }
    _fieldDependencyDeclarations.put(beanClazz, fieldDecls);
}
Also used : Inject(javax.inject.Inject) Field(java.lang.reflect.Field) Named(javax.inject.Named) ArrayList(java.util.ArrayList)

Example 2 with Inject

use of javax.inject.Inject in project dagger by square.

the class InjectAdapterProcessor method createInjectedClass.

/**
   * @param injectedClassName the name of a class with an @Inject-annotated member.
   */
private InjectedClass createInjectedClass(String injectedClassName) {
    TypeElement type = processingEnv.getElementUtils().getTypeElement(injectedClassName);
    boolean isAbstract = type.getModifiers().contains(ABSTRACT);
    List<Element> staticFields = new ArrayList<Element>();
    ExecutableElement constructor = null;
    List<Element> fields = new ArrayList<Element>();
    for (Element member : type.getEnclosedElements()) {
        if (member.getAnnotation(Inject.class) == null) {
            continue;
        }
        switch(member.getKind()) {
            case FIELD:
                if (member.getModifiers().contains(STATIC)) {
                    staticFields.add(member);
                } else {
                    fields.add(member);
                }
                break;
            case CONSTRUCTOR:
                if (constructor != null) {
                    // TODO(tbroyer): pass annotation information
                    error("Too many injectable constructors on " + type.getQualifiedName(), member);
                } else if (isAbstract) {
                    // TODO(tbroyer): pass annotation information
                    error("Abstract class " + type.getQualifiedName() + " must not have an @Inject-annotated constructor.", member);
                }
                constructor = (ExecutableElement) member;
                break;
            default:
                // TODO(tbroyer): pass annotation information
                error("Cannot inject " + elementToString(member), member);
                break;
        }
    }
    if (constructor == null && !isAbstract) {
        constructor = getNoArgsConstructor(type);
        if (constructor != null && !isCallableConstructor(constructor)) {
            constructor = null;
        }
    }
    return new InjectedClass(type, staticFields, constructor, fields);
}
Also used : Inject(javax.inject.Inject) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList)

Example 3 with Inject

use of javax.inject.Inject in project dagger by square.

the class ReflectiveAtInjectBinding method create.

public static <T> Binding<T> create(Class<T> type, boolean mustHaveInjections) {
    boolean singleton = type.isAnnotationPresent(Singleton.class);
    List<String> keys = new ArrayList<String>();
    // Lookup the injectable fields and their corresponding keys.
    List<Field> injectedFields = new ArrayList<Field>();
    for (Class<?> c = type; c != Object.class; c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            if (!field.isAnnotationPresent(Inject.class) || Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            if ((field.getModifiers() & Modifier.PRIVATE) != 0) {
                throw new IllegalStateException("Can't inject private field: " + field);
            }
            field.setAccessible(true);
            injectedFields.add(field);
            keys.add(Keys.get(field.getGenericType(), field.getAnnotations(), field));
        }
    }
    // Look up @Inject-annotated constructors. If there's no @Inject-annotated
    // constructor, use a default public constructor if the class has other
    // injections. Otherwise treat the class as non-injectable.
    Constructor<T> injectedConstructor = null;
    for (Constructor<T> constructor : getConstructorsForType(type)) {
        if (!constructor.isAnnotationPresent(Inject.class)) {
            continue;
        }
        if (injectedConstructor != null) {
            throw new InvalidBindingException(type.getName(), "has too many injectable constructors");
        }
        injectedConstructor = constructor;
    }
    if (injectedConstructor == null) {
        if (!injectedFields.isEmpty()) {
            try {
                injectedConstructor = type.getDeclaredConstructor();
            } catch (NoSuchMethodException ignored) {
            }
        } else if (mustHaveInjections) {
            throw new InvalidBindingException(type.getName(), "has no injectable members. Do you want to add an injectable constructor?");
        }
    }
    int parameterCount;
    String provideKey;
    if (injectedConstructor != null) {
        if ((injectedConstructor.getModifiers() & Modifier.PRIVATE) != 0) {
            throw new IllegalStateException("Can't inject private constructor: " + injectedConstructor);
        }
        provideKey = Keys.get(type);
        injectedConstructor.setAccessible(true);
        Type[] types = injectedConstructor.getGenericParameterTypes();
        parameterCount = types.length;
        if (parameterCount != 0) {
            Annotation[][] annotations = injectedConstructor.getParameterAnnotations();
            for (int p = 0; p < types.length; p++) {
                keys.add(Keys.get(types[p], annotations[p], injectedConstructor));
            }
        }
    } else {
        provideKey = null;
        parameterCount = 0;
        if (singleton) {
            throw new IllegalArgumentException("No injectable constructor on @Singleton " + type.getName());
        }
    }
    Class<? super T> supertype = type.getSuperclass();
    if (supertype != null) {
        if (Keys.isPlatformType(supertype.getName())) {
            supertype = null;
        } else {
            keys.add(Keys.getMembersKey(supertype));
        }
    }
    String membersKey = Keys.getMembersKey(type);
    return new ReflectiveAtInjectBinding<T>(provideKey, membersKey, singleton, type, injectedFields.toArray(new Field[injectedFields.size()]), injectedConstructor, parameterCount, supertype, keys.toArray(new String[keys.size()]));
}
Also used : Inject(javax.inject.Inject) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) Type(java.lang.reflect.Type)

Example 4 with Inject

use of javax.inject.Inject in project toydi by tokuhirom.

the class ToyDI method instantiateMembers.

public void instantiateMembers(Object object) throws IllegalAccessException, InstantiationException {
    for (final Field field : object.getClass().getDeclaredFields()) {
        Inject inject = field.getAnnotation(Inject.class);
        if (inject != null) {
            field.setAccessible(true);
            final Class<?> type = field.getType();
            Object value = this.getInstance(type);
            field.set(object, value);
        }
    }
}
Also used : Inject(javax.inject.Inject) Field(java.lang.reflect.Field)

Example 5 with Inject

use of javax.inject.Inject in project gradle by gradle.

the class AbstractClassGenerator method inspectType.

private void inspectType(Class<?> type, ClassMetaData classMetaData) {
    ClassDetails classDetails = ClassInspector.inspect(type);
    boolean hasGetServicesMethod = false;
    for (Method method : classDetails.getAllMethods()) {
        if (method.getAnnotation(Inject.class) != null) {
            if (!Modifier.isPublic(method.getModifiers()) && !Modifier.isProtected(method.getModifiers())) {
                throw new UnsupportedOperationException(String.format("Cannot attach @Inject to method %s.%s() as it is not public or protected.", method.getDeclaringClass().getSimpleName(), method.getName()));
            }
            if (Modifier.isStatic(method.getModifiers())) {
                throw new UnsupportedOperationException(String.format("Cannot attach @Inject to method %s.%s() as it is static.", method.getDeclaringClass().getSimpleName(), method.getName()));
            }
        }
        if ("getServices".equals(method.getName()) && (method.getParameterTypes().length == 0) && ServiceRegistry.class.equals(method.getReturnType())) {
            hasGetServicesMethod = true;
        }
    }
    for (PropertyDetails property : classDetails.getProperties()) {
        PropertyMetaData propertyMetaData = classMetaData.property(property.getName());
        for (Method method : property.getGetters()) {
            propertyMetaData.addGetter(method);
        }
        for (Method method : property.getSetters()) {
            propertyMetaData.addSetter(method);
        }
    }
    for (Method method : classDetails.getInstanceMethods()) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 1) {
            classMetaData.addCandidateSetMethod(method);
        }
        if (parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].equals(Action.class)) {
            classMetaData.addActionMethod(method);
        } else if (parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].equals(Closure.class)) {
            classMetaData.addClosureMethod(method);
        }
    }
    if (!hasGetServicesMethod) {
        for (PropertyMetaData metaData : classMetaData.properties.values()) {
            if (metaData.injector) {
                classMetaData.shouldImplementWithServiceRegistry = true;
            }
        }
    }
}
Also used : Inject(javax.inject.Inject) Action(org.gradle.api.Action) PropertyDetails(org.gradle.internal.reflect.PropertyDetails) Method(java.lang.reflect.Method) ServiceRegistry(org.gradle.internal.service.ServiceRegistry) ClassDetails(org.gradle.internal.reflect.ClassDetails)

Aggregations

Inject (javax.inject.Inject)23 Field (java.lang.reflect.Field)8 Provides (com.google.inject.Provides)6 ArrayList (java.util.ArrayList)5 Named (javax.inject.Named)5 Singleton (javax.inject.Singleton)3 Element (javax.lang.model.element.Element)2 Crypto (org.apache.ws.security.components.crypto.Crypto)2 Bundle (android.os.Bundle)1 AppCompatActivity (android.support.v7.app.AppCompatActivity)1 TextView (android.widget.TextView)1 Toast (android.widget.Toast)1 RestLiInternalException (com.linkedin.restli.internal.server.RestLiInternalException)1 AnnotationSet (com.linkedin.restli.internal.server.model.AnnotationSet)1 Annotation (java.lang.annotation.Annotation)1 Constructor (java.lang.reflect.Constructor)1 Method (java.lang.reflect.Method)1 Type (java.lang.reflect.Type)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1