net.bytebuddy.description.method.MethodList Java Examples

The following examples show how to use net.bytebuddy.description.method.MethodList. 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: MethodRegistryDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMultipleRegistryDoesNotPrepareMultipleTimes() throws Exception {
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    when(firstFilter.matches(instrumentedMethod)).thenReturn(true);
    when(secondFilter.matches(instrumentedMethod)).thenReturn(true);
    MethodRegistry.Prepared methodRegistry = new MethodRegistry.Default()
            .append(firstMatcher, firstHandler, firstFactory, transformer)
            .append(firstMatcher, firstHandler, firstFactory, transformer)
            .append(secondMatcher, firstHandler, firstFactory, transformer)
            .append(secondMatcher, firstHandler, secondFactory, transformer)
            .append(secondMatcher, secondHandler, secondFactory, transformer)
            .append(firstMatcher, secondHandler, secondFactory, transformer)
            .append(firstMatcher, firstHandler, secondFactory, transformer)
            .append(firstMatcher, secondHandler, firstFactory, transformer)
            .prepare(firstType, methodGraphCompiler, TypeValidation.ENABLED, VisibilityBridgeStrategy.Default.ALWAYS, methodFilter);
    assertThat(methodRegistry.getInstrumentedType(), is(typeDescription));
    assertThat(methodRegistry.getInstrumentedMethods(), is((MethodList) new MethodList.Explicit(instrumentedMethod)));
    assertThat(methodRegistry.getTypeInitializer(), is(typeInitializer));
    assertThat(methodRegistry.getLoadedTypeInitializer(), is(loadedTypeInitializer));
    verify(firstHandler).prepare(firstType);
    verify(secondHandler).prepare(secondType);
}
 
Example #2
Source File: PropertyAccessorCollector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
protected StackManipulation invocationOperation(
        AnnotatedMember annotatedMember, TypeDefinition beanClassDescription) {

    final String methodName = annotatedMember.getName();
    @SuppressWarnings("unchecked")
    final MethodList<MethodDescription> matchingMethods =
            (MethodList<MethodDescription>) beanClassDescription.getDeclaredMethods().filter(named(methodName));

    if (matchingMethods.size() == 1) { //method was declared on class
        return MethodInvocation.invoke(matchingMethods.getOnly());
    }
    if (matchingMethods.isEmpty()) { //method was not found on class, try super class
        return invocationOperation(annotatedMember, beanClassDescription.getSuperClass());
    }
    else { //should never happen
        throw new IllegalStateException("Could not find definition of method: " + methodName);
    }
}
 
Example #3
Source File: PropertyMutatorCollector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
protected StackManipulation invocationOperation(AnnotatedMember annotatedMember,
        TypeDefinition beanClassDescription) {

    final String methodName = annotatedMember.getName();
    @SuppressWarnings("unchecked")
    final MethodList<MethodDescription> matchingMethods =
            (MethodList<MethodDescription>) beanClassDescription.getDeclaredMethods().filter(named(methodName));

    if (matchingMethods.size() == 1) { //method was declared on class
        return MethodInvocation.invoke(matchingMethods.getOnly());
    }
    if (matchingMethods.isEmpty()) { //method was not found on class, try super class
        return invocationOperation(annotatedMember, beanClassDescription.getSuperClass());
    }
    else { //should never happen
        throw new IllegalStateException("Could not find definition of method: " + methodName);
    }

}
 
Example #4
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodRegistry inject(TypeDescription instrumentedType, MethodRegistry methodRegistry) {
    MethodList<?> candidates = instrumentedType.getSuperClass().getDeclaredMethods().filter(isConstructor().and(elementMatcher));
    if (candidates.isEmpty()) {
        throw new IllegalStateException("No possible candidate for super constructor invocation in " + instrumentedType.getSuperClass());
    } else if (!candidates.filter(takesArguments(0)).isEmpty()) {
        candidates = candidates.filter(takesArguments(0));
    } else if (candidates.size() > 1) {
        throw new IllegalStateException("More than one possible super constructor for constructor delegation: " + candidates);
    }
    MethodCall methodCall = MethodCall.invoke(candidates.getOnly());
    for (TypeDescription typeDescription : candidates.getOnly().getParameters().asTypeList().asErasures()) {
        methodCall = methodCall.with(typeDescription.getDefaultValue());
    }
    return methodRegistry.append(new LatentMatcher.Resolved<MethodDescription>(isConstructor().and(takesArguments(0))),
            new MethodRegistry.Handler.ForImplementation(methodCall),
            methodAttributeAppenderFactory,
            Transformer.NoOp.<MethodDescription>make());
}
 
Example #5
Source File: AsmVisitorWrapperForDeclaredFieldsTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknown() throws Exception {
    assertThat(new AsmVisitorWrapper.ForDeclaredFields()
            .field(matcher, fieldVisitorWrapper)
            .wrap(instrumentedType,
                    classVisitor,
                    implementationContext,
                    typePool,
                    new FieldList.Explicit<FieldDescription.InDefinedShape>(foo, bar),
                    new MethodList.Empty<MethodDescription>(),
                    IRRELEVANT,
                    IRRELEVANT)
            .visitField(MODIFIERS, FOO + BAR, QUX, BAZ, QUX + BAZ), is(fieldVisitor));
    verifyZeroInteractions(matcher);
    verifyZeroInteractions(fieldVisitorWrapper);
}
 
Example #6
Source File: MethodAttributeAppenderForInstrumentedMethodTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testJdkTypeIsFiltered() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    AnnotationDescription annotationDescription = mock(AnnotationDescription.class);
    TypeDescription annotationType = mock(TypeDescription.class);
    when(annotationType.getDeclaredMethods()).thenReturn(new MethodList.Empty<MethodDescription.InDefinedShape>());
    when(annotationDescription.getRetention()).thenReturn(RetentionPolicy.RUNTIME);
    when(annotationDescription.getAnnotationType()).thenReturn(annotationType);
    when(annotationType.getActualName()).thenReturn("jdk.internal.Sample");
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(annotationDescription));
    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.Empty());
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verifyZeroInteractions(methodVisitor);
}
 
Example #7
Source File: TransformerInvokerGenerator.java    From Diorite with MIT License 6 votes vote down vote up
@Override
        public ClassVisitor wrap(TypeDescription typeDescription, ClassVisitor cv, Context context, TypePool typePool,
                                 FieldList<FieldDescription.InDefinedShape> fieldList, MethodList<?> methodList, int i, int i1)
        {
//            public void visit(int version, int modifiers, String name, String signature, String superName, String[] interfaces) {
            cv.visit(ClassFileVersion.JAVA_V9.getMinorMajorVersion(), typeDescription.getModifiers(), typeDescription.getInternalName(), null,
                     typeDescription.getSuperClass().asErasure().getInternalName(), typeDescription.getInterfaces().asErasures().toInternalNames());
            TypeDescription clazz = this.clazz;
            String internalName = clazz.getInternalName();
            String descriptor = clazz.getDescriptor();
            MethodList<InDefinedShape> declaredMethods = clazz.getDeclaredMethods();
            int methodsSize = declaredMethods.size();
            String implName = GENERATED_PREFIX + "." + clazz.getName();
            String internalImplName = GENERATED_PREFIX.replace('.', '/') + "/" + internalName;
            String descriptorImplName = "L" + GENERATED_PREFIX.replace('.', '/') + "/" + internalName + ";";

            FieldVisitor fv;
            MethodVisitor mv;
            AnnotationVisitor av0;

            cv.visitEnd();
            return cv;
        }
 
Example #8
Source File: TypeWriterFieldPoolRecordTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(fieldDescription.getActualModifiers()).thenReturn(MODIFIER);
    when(fieldDescription.getInternalName()).thenReturn(FOO);
    when(fieldDescription.getDescriptor()).thenReturn(BAR);
    when(fieldDescription.getGenericSignature()).thenReturn(QUX);
    when(fieldDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(annotationDescription));
    when(fieldDescription.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(classVisitor.visitField(MODIFIER, FOO, BAR, QUX, defaultValue)).thenReturn(fieldVisitor);
    when(classVisitor.visitField(MODIFIER, FOO, BAR, QUX, FieldDescription.NO_DEFAULT_VALUE)).thenReturn(fieldVisitor);
    when(annotationValueFilterFactory.on(fieldDescription)).thenReturn(valueFilter);
    when(fieldVisitor.visitAnnotation(any(String.class), anyBoolean())).thenReturn(annotationVisitor);
    when(annotationDescription.getAnnotationType()).thenReturn(annotationType);
    when(annotationType.getDescriptor()).thenReturn(BAZ);
    when(annotationType.getDeclaredMethods()).thenReturn(new MethodList.Empty<MethodDescription.InDefinedShape>());
    when(annotationDescription.getRetention()).thenReturn(RetentionPolicy.RUNTIME);
}
 
Example #9
Source File: MethodRegistryDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMatchedFirst() throws Exception {
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    when(firstFilter.matches(instrumentedMethod)).thenReturn(true);
    MethodRegistry.Prepared methodRegistry = new MethodRegistry.Default()
            .append(firstMatcher, firstHandler, firstFactory, transformer)
            .append(secondMatcher, secondHandler, secondFactory, transformer)
            .prepare(firstType, methodGraphCompiler, TypeValidation.ENABLED, VisibilityBridgeStrategy.Default.ALWAYS, methodFilter);
    assertThat(methodRegistry.getInstrumentedType(), is(typeDescription));
    assertThat(methodRegistry.getInstrumentedMethods(), is((MethodList) new MethodList.Explicit(instrumentedMethod)));
    assertThat(methodRegistry.getTypeInitializer(), is(typeInitializer));
    assertThat(methodRegistry.getLoadedTypeInitializer(), is(loadedTypeInitializer));
    verify(firstHandler).prepare(firstType);
    verify(secondHandler).prepare(secondType);
}
 
Example #10
Source File: MethodRegistryDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCompiledAppendingMatchesSecondAppendedIfFirstDoesNotMatch() throws Exception {
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    when(firstFilter.matches(instrumentedMethod)).thenReturn(false);
    when(secondFilter.matches(instrumentedMethod)).thenReturn(true);
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    MethodRegistry.Compiled methodRegistry = new MethodRegistry.Default()
            .append(firstMatcher, firstHandler, firstFactory, transformer)
            .append(secondMatcher, secondHandler, secondFactory, transformer)
            .prepare(firstType, methodGraphCompiler, TypeValidation.ENABLED, VisibilityBridgeStrategy.Default.ALWAYS, methodFilter)
            .compile(implementationTargetFactory, classFileVersion);
    assertThat(methodRegistry.getInstrumentedType(), is(typeDescription));
    assertThat(methodRegistry.getInstrumentedMethods(), is((MethodList) new MethodList.Explicit(instrumentedMethod)));
    assertThat(methodRegistry.getTypeInitializer(), is(typeInitializer));
    assertThat(methodRegistry.getLoadedTypeInitializer(), is(loadedTypeInitializer));
    verify(firstHandler).prepare(firstType);
    verify(secondHandler).prepare(secondType);
    verifyZeroInteractions(firstFactory);
    verify(secondFactory).make(typeDescription);
    assertThat(methodRegistry.target(instrumentedMethod), is(secondRecord));
}
 
Example #11
Source File: TypeWriterRecordComponentPoolRecordTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(recordComponentDescription.getActualName()).thenReturn(FOO);
    when(recordComponentDescription.getDescriptor()).thenReturn(BAR);
    when(recordComponentDescription.getGenericSignature()).thenReturn(QUX);
    when(recordComponentDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(annotationDescription));
    when(recordComponentDescription.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(classVisitor.visitRecordComponent(FOO, BAR, QUX)).thenReturn(recordComponentVisitor);
    when(classVisitor.visitRecordComponent(FOO, BAR, QUX)).thenReturn(recordComponentVisitor);
    when(annotationValueFilterFactory.on(recordComponentDescription)).thenReturn(valueFilter);
    when(recordComponentVisitor.visitAnnotation(any(String.class), anyBoolean())).thenReturn(annotationVisitor);
    when(annotationDescription.getAnnotationType()).thenReturn(annotationType);
    when(annotationType.getDescriptor()).thenReturn(BAZ);
    when(annotationType.getDeclaredMethods()).thenReturn(new MethodList.Empty<MethodDescription.InDefinedShape>());
    when(annotationDescription.getRetention()).thenReturn(RetentionPolicy.RUNTIME);
}
 
Example #12
Source File: MethodRegistryDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCompiledAppendingMatchesFirstAppended() throws Exception {
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    when(firstFilter.matches(instrumentedMethod)).thenReturn(true);
    when(secondFilter.matches(instrumentedMethod)).thenReturn(true);
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    MethodRegistry.Compiled methodRegistry = new MethodRegistry.Default()
            .append(firstMatcher, firstHandler, firstFactory, transformer)
            .append(secondMatcher, secondHandler, secondFactory, transformer)
            .prepare(firstType, methodGraphCompiler, TypeValidation.ENABLED, VisibilityBridgeStrategy.Default.ALWAYS, methodFilter)
            .compile(implementationTargetFactory, classFileVersion);
    assertThat(methodRegistry.getInstrumentedType(), is(typeDescription));
    assertThat(methodRegistry.getInstrumentedMethods(), is((MethodList) new MethodList.Explicit(instrumentedMethod)));
    assertThat(methodRegistry.getTypeInitializer(), is(typeInitializer));
    assertThat(methodRegistry.getLoadedTypeInitializer(), is(loadedTypeInitializer));
    verify(firstHandler).prepare(firstType);
    verify(secondHandler).prepare(secondType);
    verify(firstFactory).make(typeDescription);
    verifyZeroInteractions(secondFactory);
    assertThat(methodRegistry.target(instrumentedMethod), is(firstRecord));
}
 
Example #13
Source File: MemberRemoval.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    Map<String, FieldDescription.InDefinedShape> mappedFields = new HashMap<String, FieldDescription.InDefinedShape>();
    for (FieldDescription.InDefinedShape fieldDescription : fields) {
        mappedFields.put(fieldDescription.getInternalName() + fieldDescription.getDescriptor(), fieldDescription);
    }
    Map<String, MethodDescription> mappedMethods = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mappedMethods.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new MemberRemovingClassVisitor(classVisitor, fieldMatcher, methodMatcher, mappedFields, mappedMethods);
}
 
Example #14
Source File: ModifierAdjustment.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ModifierAdjustingClassVisitor wrap(TypeDescription instrumentedType,
                                          ClassVisitor classVisitor,
                                          Implementation.Context implementationContext,
                                          TypePool typePool,
                                          FieldList<FieldDescription.InDefinedShape> fields,
                                          MethodList<?> methods,
                                          int writerFlags,
                                          int readerFlags) {
    Map<String, FieldDescription.InDefinedShape> mappedFields = new HashMap<String, FieldDescription.InDefinedShape>();
    for (FieldDescription.InDefinedShape fieldDescription : fields) {
        mappedFields.put(fieldDescription.getInternalName() + fieldDescription.getDescriptor(), fieldDescription);
    }
    Map<String, MethodDescription> mappedMethods = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mappedMethods.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new ModifierAdjustingClassVisitor(classVisitor,
            typeAdjustments,
            fieldAdjustments,
            methodAdjustments,
            instrumentedType,
            mappedFields,
            mappedMethods);
}
 
Example #15
Source File: AsmVisitorWrapperForDeclaredMethodsTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchedInvokable() throws Exception {
    assertThat(new AsmVisitorWrapper.ForDeclaredMethods()
            .invokable(matcher, methodVisitorWrapper)
            .wrap(instrumentedType,
                    classVisitor,
                    implementationContext,
                    typePool,
                    new FieldList.Empty<FieldDescription.InDefinedShape>(),
                    new MethodList.Explicit<MethodDescription>(foo, bar),
                    FLAGS,
                    FLAGS * 2)
            .visitMethod(MODIFIERS, FOO, QUX, BAZ, new String[]{QUX + BAZ}), is(wrappedVisitor));
    verify(matcher).matches(foo);
    verifyNoMoreInteractions(matcher);
    verify(methodVisitorWrapper).wrap(instrumentedType, foo, methodVisitor, implementationContext, typePool, FLAGS, FLAGS * 2);
    verifyNoMoreInteractions(methodVisitorWrapper);
    verifyZeroInteractions(typePool);
}
 
Example #16
Source File: TypePoolDefaultComponentPoolStrategyTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testForAnnotationProperty() throws Exception {
    TypePool typePool = mock(TypePool.class);
    TypeDescription typeDescription = mock(TypeDescription.class);
    when(typePool.describe(BAR)).thenReturn(new TypePool.Resolution.Simple(typeDescription));
    MethodDescription.InDefinedShape methodDescription = mock(MethodDescription.InDefinedShape.class);
    when(typeDescription.getDeclaredMethods()).thenReturn(new MethodList.Explicit<MethodDescription.InDefinedShape>(methodDescription));
    when(methodDescription.getActualName()).thenReturn(FOO);
    TypeDescription.Generic returnType = mock(TypeDescription.Generic.class);
    TypeDescription rawReturnType = mock(TypeDescription.class);
    when(returnType.asErasure()).thenReturn(rawReturnType);
    when(methodDescription.getReturnType()).thenReturn(returnType);
    TypeDescription rawComponentType = mock(TypeDescription.class);
    when(rawReturnType.getComponentType()).thenReturn(rawComponentType);
    when(rawComponentType.getName()).thenReturn(QUX);
    assertThat(new TypePool.Default.ComponentTypeLocator.ForAnnotationProperty(typePool, BAR_DESCRIPTOR).bind(FOO).lookup(), is(QUX));
}
 
Example #17
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    Map<String, MethodDescription> mapped = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mapped.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new DispatchingVisitor(classVisitor,
            instrumentedType,
            implementationContext,
            typePool,
            mapped,
            writerFlags,
            readerFlags);
}
 
Example #18
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    for (AsmVisitorWrapper asmVisitorWrapper : asmVisitorWrappers) {
        classVisitor = asmVisitorWrapper.wrap(instrumentedType,
                classVisitor,
                implementationContext,
                typePool,
                fields,
                methods,
                writerFlags,
                readerFlags);
    }
    return classVisitor;
}
 
Example #19
Source File: MethodRegistryDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCompiledPrependingMatchesLastPrepended() throws Exception {
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    when(firstFilter.matches(instrumentedMethod)).thenReturn(true);
    when(secondFilter.matches(instrumentedMethod)).thenReturn(true);
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    MethodRegistry.Compiled methodRegistry = new MethodRegistry.Default()
            .append(secondMatcher, secondHandler, secondFactory, transformer)
            .prepend(firstMatcher, firstHandler, firstFactory, transformer)
            .prepare(firstType, methodGraphCompiler, TypeValidation.ENABLED, VisibilityBridgeStrategy.Default.ALWAYS, methodFilter)
            .compile(implementationTargetFactory, classFileVersion);
    assertThat(methodRegistry.getInstrumentedType(), is(typeDescription));
    assertThat(methodRegistry.getInstrumentedMethods(), is((MethodList) new MethodList.Explicit(instrumentedMethod)));
    assertThat(methodRegistry.getTypeInitializer(), is(typeInitializer));
    assertThat(methodRegistry.getLoadedTypeInitializer(), is(loadedTypeInitializer));
    verify(firstHandler).prepare(firstType);
    verify(secondHandler).prepare(secondType);
    verify(firstFactory).make(typeDescription);
    verifyZeroInteractions(secondFactory);
    assertThat(methodRegistry.target(instrumentedMethod), is(firstRecord));
}
 
Example #20
Source File: TypeConstantAdjustmentTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstrumentationModernClassFile() throws Exception {
    ClassVisitor classVisitor = TypeConstantAdjustment.INSTANCE.wrap(mock(TypeDescription.class),
            this.classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED);
    classVisitor.visit(ClassFileVersion.JAVA_V5.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    assertThat(classVisitor.visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ}), is(methodVisitor));
    verify(this.classVisitor).visit(ClassFileVersion.JAVA_V5.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verify(this.classVisitor).visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verifyNoMoreInteractions(this.classVisitor);
    verifyZeroInteractions(methodVisitor);
}
 
Example #21
Source File: HashCodeAndEqualsPlugin.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Override
protected EqualsMethod equalsMethod(TypeDescription instrumentedType) {
    TypeDefinition typeDefinition = instrumentedType.getSuperClass();
    while (typeDefinition != null && !typeDefinition.represents(Object.class)) {
        if (typeDefinition.asErasure().getDeclaredAnnotations().isAnnotationPresent(Enhance.class)) {
            return EqualsMethod.requiringSuperClassEquality();
        }
        MethodList<?> hashCode = typeDefinition.getDeclaredMethods().filter(isHashCode());
        if (!hashCode.isEmpty()) {
            return hashCode.getOnly().isAbstract()
                    ? EqualsMethod.isolated()
                    : EqualsMethod.requiringSuperClassEquality();
        }
        typeDefinition = typeDefinition.getSuperClass().asErasure();
    }
    return EqualsMethod.isolated();
}
 
Example #22
Source File: MethodOverrideMatcherTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(declaredTypeMethod.isVirtual()).thenReturn(true);
    when(superTypeMethod.isVirtual()).thenReturn(true);
    when(interfaceTypeMethod.isVirtual()).thenReturn(true);
    when(methodDescription.getDeclaringType()).thenReturn(declaringType);
    when(methodDescription.asSignatureToken()).thenReturn(token);
    when(declaringType.asGenericType()).thenReturn(declaringType);
    when(superType.asGenericType()).thenReturn(superType);
    when(interfaceType.asGenericType()).thenReturn(interfaceType);
    when(declaringType.asErasure()).thenReturn(rawDeclaringType);
    when(superType.asErasure()).thenReturn(rawSuperType);
    when(interfaceType.asErasure()).thenReturn(rawInterfaceType);
    when(declaringType.iterator()).thenReturn(Arrays.<TypeDefinition>asList(declaringType, superType).iterator());
    when(declaringType.getInterfaces()).thenReturn(new TypeList.Generic.Explicit(interfaceType));
    when(superType.getInterfaces()).thenReturn(new TypeList.Generic.Empty());
    when(interfaceType.getInterfaces()).thenReturn(new TypeList.Generic.Empty());
    when(declaringType.getDeclaredMethods()).thenReturn(new MethodList.Explicit<MethodDescription.InGenericShape>(declaredTypeMethod));
    when(superType.getDeclaredMethods()).thenReturn(new MethodList.Explicit<MethodDescription.InGenericShape>(superTypeMethod));
    when(interfaceType.getDeclaredMethods()).thenReturn(new MethodList.Explicit<MethodDescription.InGenericShape>(interfaceTypeMethod));
}
 
Example #23
Source File: AsmVisitorWrapperForDeclaredMethodsTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonMatchedInvokable() throws Exception {
    assertThat(new AsmVisitorWrapper.ForDeclaredMethods()
            .invokable(matcher, methodVisitorWrapper)
            .wrap(instrumentedType,
                    classVisitor,
                    implementationContext,
                    typePool,
                    new FieldList.Empty<FieldDescription.InDefinedShape>(),
                    new MethodList.Explicit<MethodDescription>(foo, bar),
                    FLAGS,
                    FLAGS * 2)
            .visitMethod(MODIFIERS, BAR, BAZ, BAZ, new String[]{QUX + BAZ}), is(methodVisitor));
    verify(matcher).matches(bar);
    verifyNoMoreInteractions(matcher);
    verifyZeroInteractions(methodVisitorWrapper);
    verifyZeroInteractions(typePool);
}
 
Example #24
Source File: DeclaringMethodMatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMatch() throws Exception {
    when(typeDescription.getDeclaredMethods()).thenReturn((MethodList) methodList);
    when(methodMatcher.matches(methodList)).thenReturn(true);
    assertThat(new DeclaringMethodMatcher<TypeDescription>(methodMatcher).matches(typeDescription), is(true));
    verify(methodMatcher).matches(methodList);
    verifyNoMoreInteractions(methodMatcher);
    verify(typeDescription).getDeclaredMethods();
    verifyNoMoreInteractions(typeDescription);
}
 
Example #25
Source File: DeclaringMethodMatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testNoMatch() throws Exception {
    when(typeDescription.getDeclaredMethods()).thenReturn((MethodList) methodList);
    when(methodMatcher.matches(methodList)).thenReturn(false);
    assertThat(new DeclaringMethodMatcher<TypeDescription>(methodMatcher).matches(typeDescription), is(false));
    verify(methodMatcher).matches(methodList);
    verifyNoMoreInteractions(methodMatcher);
    verify(typeDescription).getDeclaredMethods();
    verifyNoMoreInteractions(typeDescription);
}
 
Example #26
Source File: AsmVisitorWrapperNoOpTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapperChain() throws Exception {
    ClassVisitor classVisitor = mock(ClassVisitor.class);
    assertThat(AsmVisitorWrapper.NoOp.INSTANCE.wrap(mock(TypeDescription.class),
            classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED), is(classVisitor));
    verifyZeroInteractions(classVisitor);
}
 
Example #27
Source File: SubclassImplementationTarget.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a special method invocation for a constructor invocation.
 *
 * @param token A token describing the constructor to be invoked.
 * @return A special method invocation for a constructor representing the given method token, if available.
 */
private Implementation.SpecialMethodInvocation invokeConstructor(MethodDescription.SignatureToken token) {
    TypeDescription.Generic superClass = instrumentedType.getSuperClass();
    MethodList<?> candidates = superClass == null
            ? new MethodList.Empty<MethodDescription.InGenericShape>()
            : superClass.getDeclaredMethods().filter(hasSignature(token).and(isVisibleTo(instrumentedType)));
    return candidates.size() == 1
            ? Implementation.SpecialMethodInvocation.Simple.of(candidates.getOnly(), instrumentedType.getSuperClass().asErasure())
            : Implementation.SpecialMethodInvocation.Illegal.INSTANCE;
}
 
Example #28
Source File: TypePoolDefaultLazyTypeContainmentTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testDeclaredInMethodGetMethodIsNull() throws Exception {
    MethodDescription.InDefinedShape methodDescription = mock(MethodDescription.InDefinedShape.class);
    when(methodDescription.getActualName()).thenReturn(BAR);
    when(methodDescription.getDescriptor()).thenReturn(QUX);
    TypeDescription typeDescription = mock(TypeDescription.class);
    TypePool typePool = mock(TypePool.class);
    when(typePool.describe(FOO)).thenReturn(new TypePool.Resolution.Simple(typeDescription));
    when(typeDescription.getDeclaredMethods()).thenReturn((MethodList) new MethodList.Explicit<MethodDescription>(methodDescription));
    assertThat(new TypePool.Default.LazyTypeDescription.TypeContainment.WithinMethod(FOO_INTERNAL, BAR, QUX).getEnclosingMethod(typePool),
            is(methodDescription));
}
 
Example #29
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
protected List<MethodDescription.Token> doExtractConstructors(TypeDescription instrumentedType) {
    TypeDescription.Generic superClass = instrumentedType.getSuperClass();
    MethodList<?> defaultConstructors = superClass == null
            ? new MethodList.Empty<MethodDescription.InGenericShape>()
            : superClass.getDeclaredMethods().filter(isConstructor().and(takesArguments(0)).<MethodDescription>and(isVisibleTo(instrumentedType)));
    if (defaultConstructors.size() == 1) {
        return Collections.singletonList(new MethodDescription.Token(Opcodes.ACC_PUBLIC));
    } else {
        throw new IllegalArgumentException(instrumentedType.getSuperClass() + " declares no constructor that is visible to " + instrumentedType);
    }
}
 
Example #30
Source File: MethodGraph.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms this list of nodes into a list of the node's representatives.
 *
 * @return A list of these node's representatives.
 */
public MethodList<?> asMethodList() {
    List<MethodDescription> methodDescriptions = new ArrayList<MethodDescription>(size());
    for (Node node : nodes) {
        methodDescriptions.add(node.getRepresentative());
    }
    return new MethodList.Explicit<MethodDescription>(methodDescriptions);
}