Search in sources :

Example 86 with Annotation

use of java.lang.annotation.Annotation in project byte-buddy by raphw.

the class SubclassDynamicTypeBuilderTest method testReceiverTypeInterception.

@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testReceiverTypeInterception() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = new TypeDescription.ForLoadedType(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Method method = createPlain().method(named("toString")).intercept(StubMethod.INSTANCE).receiverType(TypeDescription.Generic.Builder.rawType(TargetType.class).annotate(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, BAZ).build()).build()).make().load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded().getDeclaredMethod("toString");
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveReceiverType(method).getDeclaredAnnotations().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveReceiverType(method).getDeclaredAnnotations().ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(BAZ));
}
Also used : MethodDescription(net.bytebuddy.description.method.MethodDescription) TargetType(net.bytebuddy.dynamic.TargetType) TypeDescription(net.bytebuddy.description.type.TypeDescription) StubMethod(net.bytebuddy.implementation.StubMethod) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) AbstractDynamicTypeBuilderTest(net.bytebuddy.dynamic.AbstractDynamicTypeBuilderTest) Test(org.junit.Test)

Example 87 with Annotation

use of java.lang.annotation.Annotation in project requery by requery.

the class AttributeMember method processAssociativeAnnotations.

private void processAssociativeAnnotations(ProcessingEnvironment processingEnvironment, ElementValidator validator) {
    Optional<Annotation> oneToOne = annotationOf(OneToOne.class);
    Optional<Annotation> oneToMany = annotationOf(OneToMany.class);
    Optional<Annotation> manyToOne = annotationOf(ManyToOne.class);
    Optional<Annotation> manyToMany = annotationOf(ManyToMany.class);
    oneToOne = oneToOne.isPresent() ? oneToOne : annotationOf(javax.persistence.OneToOne.class);
    oneToMany = oneToMany.isPresent() ? oneToMany : annotationOf(javax.persistence.OneToMany.class);
    manyToOne = manyToOne.isPresent() ? manyToOne : annotationOf(javax.persistence.ManyToOne.class);
    manyToMany = manyToMany.isPresent() ? manyToMany : annotationOf(javax.persistence.ManyToMany.class);
    if (Stream.of(oneToOne, oneToMany, manyToOne, manyToMany).filter(Optional::isPresent).count() > 1) {
        validator.error("Cannot have more than one associative annotation per field");
    }
    if (oneToOne.isPresent()) {
        cardinality = Cardinality.ONE_TO_ONE;
        ReflectiveAssociation reflect = new ReflectiveAssociation(oneToOne.get());
        mappedBy = reflect.mappedBy();
        cascadeActions = reflect.cascade();
        if (!isForeignKey()) {
            isReadOnly = true;
            if (!isKey()) {
                isUnique = true;
            }
        }
    }
    if (oneToMany.isPresent()) {
        isIterable = true;
        cardinality = Cardinality.ONE_TO_MANY;
        isReadOnly = true;
        ReflectiveAssociation reflect = new ReflectiveAssociation(oneToMany.get());
        mappedBy = reflect.mappedBy();
        cascadeActions = reflect.cascade();
        checkIterable(validator);
        processOrderBy();
    }
    if (manyToOne.isPresent()) {
        cardinality = Cardinality.MANY_TO_ONE;
        isForeignKey = true;
        ReflectiveAssociation reflect = new ReflectiveAssociation(manyToOne.get());
        cascadeActions = reflect.cascade();
        if (deleteAction == null) {
            deleteAction = ReferentialAction.CASCADE;
        }
        if (updateAction == null) {
            updateAction = ReferentialAction.CASCADE;
        }
    }
    if (manyToMany.isPresent()) {
        isIterable = true;
        cardinality = Cardinality.MANY_TO_MANY;
        ReflectiveAssociation reflect = new ReflectiveAssociation(manyToMany.get());
        mappedBy = reflect.mappedBy();
        cascadeActions = reflect.cascade();
        Optional<JunctionTable> junctionTable = annotationOf(JunctionTable.class);
        Optional<javax.persistence.JoinTable> joinTable = annotationOf(javax.persistence.JoinTable.class);
        if (junctionTable.isPresent()) {
            Elements elements = processingEnvironment.getElementUtils();
            associativeDescriptor = new JunctionTableAssociation(elements, this, junctionTable.get());
        } else if (joinTable.isPresent()) {
            associativeDescriptor = new JoinTableAssociation(joinTable.get());
        }
        isReadOnly = true;
        checkIterable(validator);
        processOrderBy();
    }
    if (isForeignKey()) {
        if (deleteAction == ReferentialAction.SET_NULL && !isNullable()) {
            validator.error("Cannot SET_NULL on optional attribute", ForeignKey.class);
        }
        // user mirror so generated type can be referenced
        Optional<? extends AnnotationMirror> mirror = Mirrors.findAnnotationMirror(element(), ForeignKey.class);
        if (mirror.isPresent()) {
            referencedType = mirror.flatMap(m -> Mirrors.findAnnotationValue(m, "references")).map(value -> value.getValue().toString()).orElse(null);
        } else if (!typeMirror().getKind().isPrimitive()) {
            referencedType = typeMirror().toString();
        }
    }
}
Also used : Arrays(java.util.Arrays) Nullable(io.requery.Nullable) Modifier(javax.lang.model.element.Modifier) Lazy(io.requery.Lazy) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) ForeignKey(io.requery.ForeignKey) EnumType(javax.persistence.EnumType) ConstraintMode(javax.persistence.ConstraintMode) OrderBy(io.requery.OrderBy) Locale(java.util.Locale) Map(java.util.Map) OneToOne(io.requery.OneToOne) PropertyNameStyle(io.requery.PropertyNameStyle) Enumerated(javax.persistence.Enumerated) OneToMany(io.requery.OneToMany) EnumSet(java.util.EnumSet) Index(io.requery.Index) CascadeType(javax.persistence.CascadeType) Naming(io.requery.Naming) Set(java.util.Set) ReadOnly(io.requery.ReadOnly) Element(javax.lang.model.element.Element) Types(javax.lang.model.util.Types) Version(io.requery.Version) TypeKind(javax.lang.model.type.TypeKind) ManyToOne(io.requery.ManyToOne) Basic(javax.persistence.Basic) SourceVersion(javax.lang.model.SourceVersion) GenerationType(javax.persistence.GenerationType) List(java.util.List) Cardinality(io.requery.meta.Cardinality) Stream(java.util.stream.Stream) GeneratedValue(javax.persistence.GeneratedValue) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) MapAttributeBuilder(io.requery.meta.MapAttributeBuilder) ListAttributeBuilder(io.requery.meta.ListAttributeBuilder) Key(io.requery.Key) Transient(io.requery.Transient) JunctionTable(io.requery.JunctionTable) VariableElement(javax.lang.model.element.VariableElement) SetAttributeBuilder(io.requery.meta.SetAttributeBuilder) Convert(io.requery.Convert) ReferentialAction(io.requery.ReferentialAction) Embedded(io.requery.Embedded) ElementFilter(javax.lang.model.util.ElementFilter) LinkedHashSet(java.util.LinkedHashSet) ElementKind(javax.lang.model.element.ElementKind) ExecutableElement(javax.lang.model.element.ExecutableElement) JoinColumn(javax.persistence.JoinColumn) EnumOrdinalConverter(io.requery.converter.EnumOrdinalConverter) ResultAttributeBuilder(io.requery.meta.ResultAttributeBuilder) Generated(io.requery.Generated) Order(io.requery.query.Order) AnnotationMirror(javax.lang.model.element.AnnotationMirror) CascadeAction(io.requery.CascadeAction) TypeMirror(javax.lang.model.type.TypeMirror) Column(io.requery.Column) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) FetchType(javax.persistence.FetchType) Collections(java.util.Collections) ManyToMany(io.requery.ManyToMany) AttributeBuilder(io.requery.meta.AttributeBuilder) Optional(java.util.Optional) Elements(javax.lang.model.util.Elements) Annotation(java.lang.annotation.Annotation) JunctionTable(io.requery.JunctionTable)

Example 88 with Annotation

use of java.lang.annotation.Annotation in project roboguice by roboguice.

the class UniqueAnnotationsTest method testEqualsHashCodeToString.

public void testEqualsHashCodeToString() {
    Annotation actual = UniqueAnnotations.create(31);
    Annotation expected = getClass().getFields()[0].getAnnotations()[0];
    assertEquals(expected.toString(), actual.toString());
    assertEquals(expected.hashCode(), actual.hashCode());
    assertEquals(expected, actual);
}
Also used : Annotation(java.lang.annotation.Annotation)

Example 89 with Annotation

use of java.lang.annotation.Annotation in project roboguice by roboguice.

the class InjectionPoint method computeInjectableMembers.

/**
     * Returns an ordered, immutable set of injection points for the given type. Members in
     * superclasses come before members in subclasses. Within a class, fields come before methods.
     * Overridden methods are filtered out.
     *
     * @param statics true is this method should return static members, false for instance members
     * @param errors used to record errors
     */
private static void computeInjectableMembers(final TypeLiteral<?> type, boolean statics, Errors errors, InjectableMembers injectableMembers, OverrideIndex overrideIndex, HierarchyTraversalFilter filter) {
    Class<?> rawType = type.getRawType();
    if (!isWorthScanning(filter, rawType)) {
        return;
    }
    //recursive call on parents
    Class<?> parentRawType = rawType.getSuperclass();
    if (isWorthScanning(filter, parentRawType)) {
        computeInjectableMembers(type.getSupertype(parentRawType), statics, errors, injectableMembers, overrideIndex, filter);
        overrideIndex.position = Position.MIDDLE;
    } else {
        // we're at the top of the inheritance hierarchy
        overrideIndex.position = Position.TOP;
    }
    Set<Field> allFields = filter.getAllFields(Inject.class.getName(), rawType);
    if (allFields != null) {
        for (Field field : allFields) {
            //System.out.printf("Field %s is injectable in class %s ",field.getName(),rawType.getName());
            if (Modifier.isStatic(field.getModifiers()) == statics) {
                Annotation atInject = getAtInject(field);
                if (atInject != null) {
                    //System.out.printf("Field %s is gonna be injected in class %s ",field.getName(),rawType.getName());
                    InjectableField injectableField = new InjectableField(type, field, atInject);
                    if (injectableField.jsr330 && Modifier.isFinal(field.getModifiers())) {
                        errors.cannotInjectFinalField(field);
                    }
                    injectableMembers.add(injectableField);
                }
            }
        }
    }
    Set<Method> allMethods = filter.getAllMethods(Inject.class.getName(), rawType);
    if (allMethods != null) {
        for (Method method : allMethods) {
            if (isEligibleForInjection(method, statics)) {
                Annotation atInject = getAtInject(method);
                if (atInject != null) {
                    InjectableMethod injectableMethod = new InjectableMethod(type, method, atInject);
                    if (checkForMisplacedBindingAnnotations(method, errors) || !isValidMethod(injectableMethod, errors)) {
                        boolean removed = overrideIndex.removeIfOverriddenBy(method, false, injectableMethod);
                        if (removed) {
                            logger.log(Level.WARNING, "Method: {0} is not a valid injectable method (" + "because it either has misplaced binding annotations " + "or specifies type parameters) but is overriding a method that is valid. " + "Because it is not valid, the method will not be injected. " + "To fix this, make the method a valid injectable method.", method);
                        }
                        continue;
                    }
                    if (statics) {
                        injectableMembers.add(injectableMethod);
                    } else {
                        // Forcibly remove the overriden method, otherwise we'll inject
                        // it twice.
                        overrideIndex.removeIfOverriddenBy(method, true, injectableMethod);
                        overrideIndex.add(injectableMethod);
                    }
                } else {
                    boolean removed = overrideIndex.removeIfOverriddenBy(method, false, null);
                    if (removed) {
                        logger.log(Level.WARNING, "Method: {0} is not annotated with @Inject but " + "is overriding a method that is annotated with @javax.inject.Inject.  Because " + "it is not annotated with @Inject, the method will not be injected. " + "To fix this, annotate the method with @Inject.", method);
                    }
                }
            }
        }
    }
}
Also used : Inject(com.google.inject.Inject) Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation)

Example 90 with Annotation

use of java.lang.annotation.Annotation in project roboguice by roboguice.

the class CheckedProvideUtils method findThrowingConstructor.

// safe because it's a constructor of the typeLiteral
@SuppressWarnings("unchecked")
static <T> Constructor<? extends T> findThrowingConstructor(TypeLiteral<? extends T> typeLiteral, Binder binder) {
    Class<?> rawType = typeLiteral.getRawType();
    Errors errors = new Errors(rawType);
    Constructor<?> cxtor = null;
    for (Constructor<?> constructor : rawType.getDeclaredConstructors()) {
        if (constructor.isAnnotationPresent(ThrowingInject.class)) {
            if (cxtor != null) {
                errors.addMessage("%s has more than one constructor annotated with @ThrowingInject. " + CONSTRUCTOR_RULES, rawType);
            }
            cxtor = constructor;
            Annotation misplacedBindingAnnotation = Annotations.findBindingAnnotation(errors, cxtor, ((AnnotatedElement) cxtor).getAnnotations());
            if (misplacedBindingAnnotation != null) {
                errors.misplacedBindingAnnotation(cxtor, misplacedBindingAnnotation);
            }
        }
    }
    if (cxtor == null) {
        errors.addMessage("Could not find a suitable constructor in %s. " + CONSTRUCTOR_RULES, rawType);
    }
    for (Message msg : errors.getMessages()) {
        binder.addError(msg);
    }
    return (Constructor<? extends T>) cxtor;
}
Also used : Errors(com.google.inject.internal.Errors) Message(com.google.inject.spi.Message) Constructor(java.lang.reflect.Constructor) Annotation(java.lang.annotation.Annotation)

Aggregations

Annotation (java.lang.annotation.Annotation)707 Method (java.lang.reflect.Method)171 ArrayList (java.util.ArrayList)99 Field (java.lang.reflect.Field)76 Test (org.junit.Test)66 Type (java.lang.reflect.Type)64 HashMap (java.util.HashMap)54 HashSet (java.util.HashSet)52 Map (java.util.Map)35 ParameterizedType (java.lang.reflect.ParameterizedType)34 List (java.util.List)30 Set (java.util.Set)27 InvocationTargetException (java.lang.reflect.InvocationTargetException)22 IOException (java.io.IOException)20 BindingAnnotation (com.google.inject.BindingAnnotation)17 AbstractModule (com.google.inject.AbstractModule)16 TypeElement (javax.lang.model.element.TypeElement)15 Injector (com.google.inject.Injector)14 MediaType (okhttp3.MediaType)14 AnnotatedElement (java.lang.reflect.AnnotatedElement)13