net.bytebuddy.description.annotation.AnnotationDescription Java Examples

The following examples show how to use net.bytebuddy.description.annotation.AnnotationDescription. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MethodAttributeAppenderForInstrumentedMethodTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMethodExceptionTypeTypeAnnotationRuntimeRetention() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Empty<ParameterDescription>());
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Explicit(simpleAnnotatedType));
    when(simpleAnnotatedType.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new Baz.Instance()));
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verify(methodVisitor).visitTypeAnnotation(TypeReference.newExceptionReference(0).getValue(),
            null,
            Type.getDescriptor(Baz.class),
            true);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #2
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public List<MethodDescription.Token> extractConstructors(TypeDescription instrumentedType) {
    List<ParameterDescription.Token> tokens = new ArrayList<ParameterDescription.Token>(instrumentedType.getRecordComponents().size());
    for (RecordComponentDescription.InDefinedShape recordComponent : instrumentedType.getRecordComponents()) {
        tokens.add(new ParameterDescription.Token(recordComponent.getType(),
                recordComponent.getDeclaredAnnotations().filter(targetsElement(ElementType.CONSTRUCTOR))));
    }
    return Collections.singletonList(new MethodDescription.Token(MethodDescription.CONSTRUCTOR_INTERNAL_NAME,
            Opcodes.ACC_PUBLIC,
            Collections.<TypeVariableToken>emptyList(),
            TypeDescription.Generic.VOID,
            tokens,
            Collections.<TypeDescription.Generic>emptyList(),
            Collections.<AnnotationDescription>emptyList(),
            AnnotationValue.UNDEFINED,
            TypeDescription.Generic.UNDEFINED));
}
 
Example #3
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testMethodDuplicateAnnotation() throws Exception {
    makePlainInstrumentedType()
            .withMethod(new MethodDescription.Token(FOO,
                    ModifierContributor.EMPTY_MASK,
                    Collections.<TypeVariableToken>emptyList(),
                    TypeDescription.Generic.OBJECT,
                    Collections.<ParameterDescription.Token>emptyList(),
                    Collections.<TypeDescription.Generic>emptyList(),
                    Arrays.asList(
                            AnnotationDescription.Builder.ofType(SampleAnnotation.class).build(),
                            AnnotationDescription.Builder.ofType(SampleAnnotation.class).build()
                    ), AnnotationValue.UNDEFINED,
                    TypeDescription.Generic.UNDEFINED))
            .validated();
}
 
Example #4
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnInterfaceType() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Class<?> type = create(Class.forName(SIMPLE_TYPE_ANNOTATED))
            .merge(TypeManifestation.ABSTRACT)
            .implement(TypeDescription.Generic.Builder.rawType(Callable.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, QUX * 3).build()))
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(type.getInterfaces().length, is(2));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveInterfaceType(type, 0).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveInterfaceType(type, 0).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(QUX * 2));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveInterfaceType(type, 1).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveInterfaceType(type, 1).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(QUX * 3));
}
 
Example #5
Source File: AsmUtils.java    From Diorite with MIT License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public static Annotation[] getAnnotations(Collection<AnnotationDescription> annotations)
{
    Collection<Annotation> col = new ArrayList<>(annotations.size());
    for (AnnotationDescription annotation : annotations)
    {
        TypeDescription annotationType = annotation.getAnnotationType();
        try
        {
            Class<?> forName = Class.forName(annotationType.getActualName());
            if (! forName.isAnnotation())
            {
                continue;
            }
            col.add(annotation.prepare((Class) forName).load());
        }
        catch (ClassNotFoundException ignored)
        {
        }
    }
    return col.toArray(new Annotation[col.size()]);
}
 
Example #6
Source File: Controller.java    From Diorite with MIT License 6 votes vote down vote up
@Override
protected boolean isInjectElement(AnnotatedCodeElement element)
{
    for (AnnotationDescription annotation : AsmUtils.getAnnotationList(element))
    {
        TypeDescription annotationType = annotation.getAnnotationType();
        if (annotationType.equals(INJECT))
        {
            return true;
        }
        if (annotationType.getInheritedAnnotations().isAnnotationPresent(SHORTCUT_INJECT))
        {
            return true;
        }
    }
    return false;
}
 
Example #7
Source File: MethodAnnotationMatch.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMatch(TypeDescription typeDescription) {
    for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()) {
        List<String> annotationList = new ArrayList<String>(Arrays.asList(annotations));

        AnnotationList declaredAnnotations = methodDescription.getDeclaredAnnotations();
        for (AnnotationDescription annotation : declaredAnnotations) {
            annotationList.remove(annotation.getAnnotationType().getActualName());
        }
        if (annotationList.isEmpty()) {
            return true;
        }
    }

    return false;
}
 
Example #8
Source File: MethodAttributeAppenderForInstrumentedMethodTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMethodExceptionTypeTypeAnnotationClassFileRetention() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Empty<ParameterDescription>());
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Explicit(simpleAnnotatedType));
    when(simpleAnnotatedType.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new QuxBaz.Instance()));
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verify(methodVisitor).visitTypeAnnotation(TypeReference.newExceptionReference(0).getValue(),
            null,
            Type.getDescriptor(QuxBaz.class),
            false);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #9
Source File: ConstructorStrategyDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testImitateSuperClassOpeningStrategy() throws Exception {
    assertThat(ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING.extractConstructors(instrumentedType), is(Collections.singletonList(new MethodDescription.Token(FOO,
            Opcodes.ACC_PUBLIC,
            Collections.<TypeVariableToken>emptyList(),
            typeDescription,
            Collections.<ParameterDescription.Token>emptyList(),
            Collections.<TypeDescription.Generic>emptyList(),
            Collections.<AnnotationDescription>emptyList(),
            defaultValue,
            TypeDescription.Generic.UNDEFINED))));
    assertThat(ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING.inject(instrumentedType, methodRegistry), is(methodRegistry));
    verify(methodRegistry).append(any(LatentMatcher.class),
            any(MethodRegistry.Handler.class),
            eq(MethodAttributeAppender.NoOp.INSTANCE),
            eq(Transformer.NoOp.<MethodDescription>make()));
    verifyNoMoreInteractions(methodRegistry);
    verify(instrumentedType, atLeastOnce()).getSuperClass();
    verifyNoMoreInteractions(instrumentedType);
}
 
Example #10
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testMethodIllegalTypeVariableTypeAnnotation() throws Exception {
    makePlainInstrumentedType()
            .withMethod(new MethodDescription.Token(FOO,
                    ModifierContributor.EMPTY_MASK,
                    Collections.singletonList(new TypeVariableToken(FOO,
                            Collections.singletonList(TypeDescription.Generic.OBJECT),
                            Collections.singletonList(AnnotationDescription.Builder.ofType(IncompatibleAnnotation.class).build()))),
                    TypeDescription.Generic.OBJECT,
                    Collections.<ParameterDescription.Token>emptyList(),
                    Collections.<TypeDescription.Generic>emptyList(),
                    Collections.<AnnotationDescription>emptyList(),
                    AnnotationValue.UNDEFINED,
                    TypeDescription.Generic.UNDEFINED))
            .validated();
}
 
Example #11
Source File: InstrumentedType.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public WithFlexibleName withAnnotations(List<? extends AnnotationDescription> annotationDescriptions) {
    return new Default(name,
            modifiers,
            superClass,
            typeVariables,
            interfaceTypes,
            fieldTokens,
            methodTokens,
            recordComponentTokens,
            CompoundList.of(this.annotationDescriptions, annotationDescriptions),
            typeInitializer,
            loadedTypeInitializer,
            declaringType,
            enclosingMethod,
            enclosingType,
            declaredTypes,
            anonymousClass,
            localClass,
            record,
            nestHost,
            nestMembers);
}
 
Example #12
Source File: MethodDescription.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new latent method description. All provided types are attached to this instance before they are returned.
 *
 * @param declaringType       The type that is declaring this method.
 * @param internalName        The internal name of this method.
 * @param modifiers           The modifiers of this method.
 * @param typeVariables       The type variables of the described method.
 * @param returnType          The return type of this method.
 * @param parameterTokens     The parameter tokens describing this method.
 * @param exceptionTypes      This method's exception types.
 * @param declaredAnnotations The annotations of this method.
 * @param defaultValue        The default value of this method or {@code null} if no default annotation value is defined.
 * @param receiverType        The receiver type of this method or {@code null} if the receiver type is defined implicitly.
 */
public Latent(TypeDescription declaringType,
              String internalName,
              int modifiers,
              List<? extends TypeVariableToken> typeVariables,
              TypeDescription.Generic returnType,
              List<? extends ParameterDescription.Token> parameterTokens,
              List<? extends TypeDescription.Generic> exceptionTypes,
              List<? extends AnnotationDescription> declaredAnnotations,
              AnnotationValue<?, ?> defaultValue,
              TypeDescription.Generic receiverType) {
    this.declaringType = declaringType;
    this.internalName = internalName;
    this.modifiers = modifiers;
    this.typeVariables = typeVariables;
    this.returnType = returnType;
    this.parameterTokens = parameterTokens;
    this.exceptionTypes = exceptionTypes;
    this.declaredAnnotations = declaredAnnotations;
    this.defaultValue = defaultValue;
    this.receiverType = receiverType;
}
 
Example #13
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnTypeVariableType() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Class<?> type = create(Class.forName(SIMPLE_TYPE_ANNOTATED))
            .merge(TypeManifestation.ABSTRACT)
            .typeVariable(BAR, TypeDescription.Generic.Builder.rawType(Callable.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, QUX * 4).build()))
            .annotateTypeVariable(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, QUX * 3).build())
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(type.getTypeParameters().length, is(2));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[0]).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[0]).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(QUX));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[1]).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[1]).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(QUX * 3));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[1]).ofTypeVariableBoundType(0)
            .asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[1]).ofTypeVariableBoundType(0)
            .asList().ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(QUX * 4));
}
 
Example #14
Source File: MethodAttributeAppenderForInstrumentedMethodTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMethodParameterAnnotationClassFileRetention() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    ParameterDescription parameterDescription = mock(ParameterDescription.class);
    when(parameterDescription.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(parameterDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new QuxBaz.Instance()));
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Explicit<ParameterDescription>(parameterDescription));
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Empty());
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verify(methodVisitor).visitParameterAnnotation(0, Type.getDescriptor(QuxBaz.class), false);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #15
Source File: AnnotationAppender.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public AnnotationAppender append(AnnotationDescription annotationDescription, AnnotationValueFilter annotationValueFilter, int typeReference, String typePath) {
    switch (annotationDescription.getRetention()) {
        case RUNTIME:
            doAppend(annotationDescription, true, annotationValueFilter, typeReference, typePath);
            break;
        case CLASS:
            doAppend(annotationDescription, false, annotationValueFilter, typeReference, typePath);
            break;
        case SOURCE:
            break;
        default:
            throw new IllegalStateException("Unexpected retention policy: " + annotationDescription.getRetention());
    }
    return this;
}
 
Example #16
Source File: RebaseDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testPackageRebasement() throws Exception {
    Class<?> packageType = new ByteBuddy()
            .rebase(Sample.class.getPackage(), ClassFileLocator.ForClassLoader.of(getClass().getClassLoader()))
            .annotateType(AnnotationDescription.Builder.ofType(Baz.class).build())
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(packageType.getSimpleName(), CoreMatchers.is(PackageDescription.PACKAGE_CLASS_NAME));
    assertThat(packageType.getName(), CoreMatchers.is(Sample.class.getPackage().getName() + "." + PackageDescription.PACKAGE_CLASS_NAME));
    assertThat(packageType.getModifiers(), CoreMatchers.is(PackageDescription.PACKAGE_MODIFIERS));
    assertThat(packageType.getDeclaredFields().length, CoreMatchers.is(0));
    assertThat(packageType.getDeclaredMethods().length, CoreMatchers.is(0));
    assertThat(packageType.getDeclaredAnnotations().length, CoreMatchers.is(2));
    assertThat(packageType.getAnnotation(PackageAnnotation.class), notNullValue(PackageAnnotation.class));
    assertThat(packageType.getAnnotation(Baz.class), notNullValue(Baz.class));
}
 
Example #17
Source File: AbstractAnnotationBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(sourceDeclaringType.asErasure()).thenReturn(sourceDeclaringType);
    when(targetDeclaringType.asErasure()).thenReturn(targetDeclaringType);
    when(source.getDeclaringType()).thenReturn(sourceDeclaringType);
    annotation = mock(annotationType);
    doReturn(annotationType).when(annotation).annotationType();
    annotationDescription = AnnotationDescription.ForLoadedAnnotation.of(annotation);
    when(assigner.assign(any(TypeDescription.Generic.class), any(TypeDescription.Generic.class), any(Assigner.Typing.class))).thenReturn(stackManipulation);
    when(implementationTarget.getInstrumentedType()).thenReturn(instrumentedType);
    when(implementationTarget.getOriginType()).thenReturn(instrumentedType);
    when(instrumentedType.asErasure()).thenReturn(instrumentedType);
    when(instrumentedType.iterator()).then(new Answer<Iterator<TypeDefinition>>() {
        public Iterator<TypeDefinition> answer(InvocationOnMock invocationOnMock) throws Throwable {
            return Collections.<TypeDefinition>singleton(instrumentedType).iterator();
        }
    });
    when(source.asTypeToken()).thenReturn(sourceTypeToken);
}
 
Example #18
Source File: AnnotationAppenderDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
private Class<?> makeTypeWithSuperClassAnnotation(Annotation annotation) throws Exception {
    when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS);
    classWriter.visit(ClassFileVersion.ofThisVm().getMinorMajorVersion(),
            Opcodes.ACC_PUBLIC,
            BAR.replace('.', '/'),
            null,
            Type.getInternalName(Object.class),
            null);
    AnnotationVisitor annotationVisitor = classWriter.visitTypeAnnotation(TypeReference.newSuperTypeReference(-1).getValue(),
            null,
            Type.getDescriptor(annotation.annotationType()),
            true);
    when(target.visit(any(String.class), anyBoolean())).thenReturn(annotationVisitor);
    AnnotationDescription annotationDescription = AnnotationDescription.ForLoadedAnnotation.of(annotation);
    annotationAppender.append(annotationDescription, valueFilter);
    classWriter.visitEnd();
    Class<?> bar = new ByteArrayClassLoader(getClass().getClassLoader(), Collections.singletonMap(BAR, classWriter.toByteArray())).loadClass(BAR);
    assertThat(bar.getName(), is(BAR));
    assertThat(bar.getSuperclass(), CoreMatchers.<Class<?>>is(Object.class));
    return bar;
}
 
Example #19
Source File: TypeAttributeAppender.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void apply(ClassVisitor classVisitor, TypeDescription instrumentedType, AnnotationValueFilter annotationValueFilter) {
    AnnotationAppender annotationAppender = new AnnotationAppender.Default(new AnnotationAppender.Target.OnType(classVisitor));
    AnnotationAppender.ForTypeAnnotations.ofTypeVariable(annotationAppender,
            annotationValueFilter,
            AnnotationAppender.ForTypeAnnotations.VARIABLE_ON_TYPE,
            typeVariableIndex,
            instrumentedType.getTypeVariables());
    TypeList.Generic interfaceTypes = instrumentedType.getInterfaces();
    int interfaceTypeIndex = this.interfaceTypeIndex;
    for (TypeDescription.Generic interfaceType : interfaceTypes.subList(this.interfaceTypeIndex, interfaceTypes.size())) {
        annotationAppender = interfaceType.accept(AnnotationAppender.ForTypeAnnotations.ofInterfaceType(annotationAppender,
                annotationValueFilter,
                interfaceTypeIndex++));
    }
    AnnotationList declaredAnnotations = instrumentedType.getDeclaredAnnotations();
    for (AnnotationDescription annotationDescription : declaredAnnotations.subList(annotationIndex, declaredAnnotations.size())) {
        annotationAppender = annotationAppender.append(annotationDescription, annotationValueFilter);
    }
}
 
Example #20
Source File: MethodAttributeAppenderForInstrumentedMethodTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMethodParameterAnnotationRuntimeRetention() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    ParameterDescription parameterDescription = mock(ParameterDescription.class);
    when(parameterDescription.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(parameterDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new Baz.Instance()));
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Explicit<ParameterDescription>(parameterDescription));
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Empty());
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verify(methodVisitor).visitParameterAnnotation(0, Type.getDescriptor(Baz.class), true);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #21
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnMethodParameterType() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Method method = createPlain()
            .merge(TypeManifestation.ABSTRACT)
            .defineMethod(FOO, void.class).withParameters(TypeDescription.Generic.Builder.rawType(Object.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE).build()))
            .withoutCode()
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getDeclaredMethod(FOO, Object.class);
    assertThat(method.getParameterTypes().length, is(1));
    assertThat(method.getParameterTypes()[0], is((Object) Object.class));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveParameterType(method, 0).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveParameterType(method, 0).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
}
 
Example #22
Source File: JaxRsOffsetMappingFactory.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<JaxRsPath> annotation, AdviceType adviceType) {
    return new Advice.OffsetMapping() {
        @Override
        public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {
            Object value = null;
            if (useAnnotationValueForTransactionName) {
                value = getTransactionAnnotationValueFromAnnotations(instrumentedMethod, instrumentedType);
            }
            return Target.ForStackManipulation.of(value);
        }
    };
}
 
Example #23
Source File: TargetMethodAnnotationDrivenBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ParameterBinding<?> bind(MethodDescription source, Implementation.Target implementationTarget, Assigner assigner) {
    return Argument.Binder.INSTANCE.bind(AnnotationDescription.ForLoadedAnnotation.<Argument>of(new DefaultArgument(target.getIndex())),
            source,
            target,
            implementationTarget,
            assigner,
            typing);
}
 
Example #24
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrphanedBridge() throws Exception {
    MethodDescription.SignatureToken bridgeMethod = new MethodDescription.SignatureToken("foo",
            TypeDescription.VOID,
            Collections.<TypeDescription>emptyList());
    TypeDescription typeDescription = new InstrumentedType.Default("foo",
            Opcodes.ACC_PUBLIC,
            TypeDescription.Generic.OBJECT,
            Collections.<TypeVariableToken>emptyList(),
            Collections.<TypeDescription.Generic>emptyList(),
            Collections.<FieldDescription.Token>emptyList(),
            Collections.singletonList(new MethodDescription.Token("foo",
                    Opcodes.ACC_BRIDGE,
                    TypeDescription.Generic.VOID,
                    Collections.<TypeDescription.Generic>emptyList())),
            Collections.<RecordComponentDescription.Token>emptyList(),
            Collections.<AnnotationDescription>emptyList(),
            TypeInitializer.None.INSTANCE,
            LoadedTypeInitializer.NoOp.INSTANCE,
            TypeDescription.UNDEFINED,
            MethodDescription.UNDEFINED,
            TypeDescription.UNDEFINED,
            Collections.<TypeDescription>emptyList(),
            false,
            false,
            false,
            TargetType.DESCRIPTION,
            Collections.<TypeDescription>emptyList());
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(1 + TypeDescription.OBJECT.getDeclaredMethods().filter(ElementMatchers.isVirtual()).size()));
    MethodGraph.Node node = methodGraph.locate(bridgeMethod);
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getRepresentative().asSignatureToken(), is(bridgeMethod));
    assertThat(node.getMethodTypes().size(), is(1));
    assertThat(node.getMethodTypes(), hasItem(bridgeMethod.asTypeToken()));
    assertThat(node.getVisibility(), is(Visibility.PACKAGE_PRIVATE));
}
 
Example #25
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testMethodParameterIncompatibleAnnotation() throws Exception {
    makePlainInstrumentedType()
            .withMethod(new MethodDescription.Token(FOO,
                    ModifierContributor.EMPTY_MASK,
                    Collections.<TypeVariableToken>emptyList(),
                    TypeDescription.Generic.OBJECT,
                    Collections.singletonList(new ParameterDescription.Token(TypeDescription.Generic.OBJECT, Collections.singletonList(
                            AnnotationDescription.Builder.ofType(IncompatibleAnnotation.class).build()
                    ))), Collections.<TypeDescription.Generic>emptyList(),
                    Collections.<AnnotationDescription>emptyList(),
                    AnnotationValue.UNDEFINED,
                    TypeDescription.Generic.UNDEFINED))
            .validated();
}
 
Example #26
Source File: TargetMethodAnnotationDrivenBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a handler for a given annotation.
 *
 * @param target          The target parameter being handled.
 * @param parameterBinder The parameter binder that should process an annotation.
 * @param annotation      An annotation instance that can be understood by this parameter binder.
 * @param typing          The typing to apply.
 * @return A handler for processing the given annotation.
 */
@SuppressWarnings("unchecked")
protected static Handler of(ParameterDescription target,
                            ParameterBinder<?> parameterBinder,
                            AnnotationDescription annotation,
                            Assigner.Typing typing) {
    return new Bound<Annotation>(target,
            (ParameterBinder<Annotation>) parameterBinder,
            (AnnotationDescription.Loadable<Annotation>) annotation.prepare(parameterBinder.getHandledType()),
            typing);
}
 
Example #27
Source File: DecoratingDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecorationWithoutAnnotationRetention() throws Exception {
    Object instance = new ByteBuddy()
            .with(AnnotationRetention.DISABLED)
            .decorate(Foo.class)
            .annotateType(AnnotationDescription.Builder.ofType(Qux.class).build())
            .ignoreAlso(new LatentMatcher.Resolved<MethodDescription>(none()))
            .visit(new AsmVisitorWrapper.ForDeclaredMethods()
                    .method(named(FOO), new AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper() {
                        public MethodVisitor wrap(TypeDescription instrumentedType,
                                                  MethodDescription instrumentedMethod,
                                                  MethodVisitor methodVisitor,
                                                  Implementation.Context implementationContext,
                                                  TypePool typePool,
                                                  int writerFlags,
                                                  int readerFlags) {
                            return new MethodVisitor(OpenedClassReader.ASM_API, methodVisitor) {
                                @Override
                                public void visitLdcInsn(Object value) {
                                    if (FOO.equals(value)) {
                                        value = BAR;
                                    }
                                    super.visitLdcInsn(value);
                                }
                            };
                        }
                    }))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getConstructor()
            .newInstance();
    assertThat(instance.getClass().getMethod(FOO).invoke(instance), is((Object) BAR));
    assertThat(instance.getClass().isAnnotationPresent(Bar.class), is(true));
    assertThat(instance.getClass().isAnnotationPresent(Qux.class), is(true));
}
 
Example #28
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void tesFieldDuplicateAnnotation() throws Exception {
    makePlainInstrumentedType()
            .withField(new FieldDescription.Token(FOO, ModifierContributor.EMPTY_MASK, TypeDescription.Generic.OBJECT, Arrays.asList(
                    AnnotationDescription.Builder.ofType(SampleAnnotation.class).build(),
                    AnnotationDescription.Builder.ofType(SampleAnnotation.class).build()
            ))).validated();
}
 
Example #29
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testInconsistentReceiverNonStaticMethod() throws Exception {
    makePlainInstrumentedType()
            .withMethod(new MethodDescription.Token(FOO,
                    ModifierContributor.EMPTY_MASK,
                    Collections.<TypeVariableToken>emptyList(),
                    TypeDescription.Generic.OBJECT,
                    Collections.<ParameterDescription.Token>emptyList(),
                    Collections.<TypeDescription.Generic>emptyList(),
                    Collections.<AnnotationDescription>emptyList(),
                    AnnotationValue.UNDEFINED,
                    TypeDescription.Generic.OBJECT))
            .validated();
}
 
Example #30
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsAnnotation() throws Exception {
    AnnotationDescription annotationDescription = TypeDescription.ForLoadedType.of(IsAnnotatedWith.class)
            .getDeclaredAnnotations().ofType(IsAnnotatedWithAnnotation.class);
    assertThat(ElementMatchers.is(IsAnnotatedWith.class.getAnnotation(IsAnnotatedWithAnnotation.class)).matches(annotationDescription), is(true));
    assertThat(ElementMatchers.is(Other.class.getAnnotation(OtherAnnotation.class)).matches(annotationDescription), is(false));
}