net.bytebuddy.implementation.bytecode.member.MethodReturn Java Examples

The following examples show how to use net.bytebuddy.implementation.bytecode.member.MethodReturn. 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: MethodDelegationChainedTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testChainingNonVoid() throws Exception {
    NonVoidInterceptor nonVoidInterceptor = new NonVoidInterceptor();

    DynamicType.Loaded<Foo> dynamicType = new ByteBuddy().subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(MethodDelegation.
                    withDefaultConfiguration()
                    .filter(isDeclaredBy(NonVoidInterceptor.class))
                    .to(nonVoidInterceptor)
                    .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredConstructor().newInstance().foo(), is(FOO));
    assertThat(nonVoidInterceptor.intercepted, is(true));
}
 
Example #2
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    FieldList<?> fieldList = instrumentedType.getDeclaredFields();
    StackManipulation[] fieldLoading = new StackManipulation[fieldList.size()];
    int index = 0;
    for (FieldDescription fieldDescription : fieldList) {
        fieldLoading[index] = new StackManipulation.Compound(
                MethodVariableAccess.loadThis(),
                MethodVariableAccess.load(instrumentedMethod.getParameters().get(index)),
                FieldAccess.forField(fieldDescription).write()
        );
        index++;
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            MethodVariableAccess.loadThis(),
            MethodInvocation.invoke(ConstructorCall.INSTANCE.objectTypeDefaultConstructor),
            new StackManipulation.Compound(fieldLoading),
            MethodReturn.VOID
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #3
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor,
                  Context implementationContext,
                  MethodDescription instrumentedMethod) {
    FieldList<?> fieldList = instrumentedType.getDeclaredFields();
    List<StackManipulation> fieldLoadings = new ArrayList<StackManipulation>(fieldList.size());
    for (FieldDescription fieldDescription : fieldList) {
        fieldLoadings.add(new StackManipulation.Compound(MethodVariableAccess.loadThis(), FieldAccess.forField(fieldDescription).read()));
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            new StackManipulation.Compound(fieldLoadings),
            MethodInvocation.invoke(accessorMethod),
            assigner.assign(accessorMethod.getReturnType(), instrumentedMethod.getReturnType(), Assigner.Typing.DYNAMIC),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #4
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Blueprint method that for applying the actual implementation.
 *
 * @param methodVisitor           The method visitor to which the implementation is applied to.
 * @param implementationContext   The implementation context for the given implementation.
 * @param instrumentedMethod      The instrumented method that is target of the implementation.
 * @param fixedValueType          A description of the type of the fixed value that is loaded by the
 *                                {@code valueLoadingInstruction}.
 * @param valueLoadingInstruction A stack manipulation that represents the loading of the fixed value onto the
 *                                operand stack.
 * @return A representation of the stack and variable array sized that are required for this implementation.
 */
protected ByteCodeAppender.Size apply(MethodVisitor methodVisitor,
                                      Context implementationContext,
                                      MethodDescription instrumentedMethod,
                                      TypeDescription.Generic fixedValueType,
                                      StackManipulation valueLoadingInstruction) {
    StackManipulation assignment = assigner.assign(fixedValueType, instrumentedMethod.getReturnType(), typing);
    if (!assignment.isValid()) {
        throw new IllegalArgumentException("Cannot return value of type " + fixedValueType + " for " + instrumentedMethod);
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            valueLoadingInstruction,
            assignment,
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new ByteCodeAppender.Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #5
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.getParameters().size() <= index) {
        throw new IllegalStateException(instrumentedMethod + " does not define a parameter with index " + index);
    }
    ParameterDescription parameterDescription = instrumentedMethod.getParameters().get(index);
    StackManipulation stackManipulation = new StackManipulation.Compound(
            MethodVariableAccess.load(parameterDescription),
            assigner.assign(parameterDescription.getType(), instrumentedMethod.getReturnType(), typing),
            MethodReturn.of(instrumentedMethod.getReturnType())
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + instrumentedMethod.getReturnType() + " to " + parameterDescription);
    }
    return new Size(stackManipulation.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #6
Source File: InvocationHandlerAdapter.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Applies an implementation that delegates to a invocation handler.
 *
 * @param methodVisitor         The method visitor for writing the byte code to.
 * @param implementationContext The implementation context for the current implementation.
 * @param instrumentedMethod    The method that is instrumented.
 * @param preparingManipulation A stack manipulation that applies any preparation to the operand stack.
 * @param fieldDescription      The field that contains the value for the invocation handler.
 * @return The size of the applied assignment.
 */
protected ByteCodeAppender.Size apply(MethodVisitor methodVisitor,
                                      Context implementationContext,
                                      MethodDescription instrumentedMethod,
                                      StackManipulation preparingManipulation,
                                      FieldDescription fieldDescription) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("It is not possible to apply an invocation handler onto the static method " + instrumentedMethod);
    }
    MethodConstant.CanCache methodConstant = privileged
            ? MethodConstant.ofPrivileged(instrumentedMethod.asDefined())
            : MethodConstant.of(instrumentedMethod.asDefined());
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            preparingManipulation,
            FieldAccess.forField(fieldDescription).read(),
            MethodVariableAccess.loadThis(),
            cached ? methodConstant.cached() : methodConstant,
            ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(argumentValuesOf(instrumentedMethod)),
            MethodInvocation.invoke(INVOCATION_HANDLER_TYPE.getDeclaredMethods().getOnly()),
            assigner.assign(TypeDescription.Generic.OBJECT, instrumentedMethod.getReturnType(), Assigner.Typing.DYNAMIC),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new ByteCodeAppender.Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #7
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isMethod()) {
        return new Simple(
                MethodVariableAccess.loadThis(),
                FieldAccess.forField(instrumentedType.getDeclaredFields().filter(named(instrumentedMethod.getName())).getOnly()).read(),
                MethodReturn.of(instrumentedMethod.getReturnType())
        ).apply(methodVisitor, implementationContext, instrumentedMethod);
    } else {
        List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(instrumentedType.getRecordComponents().size() * 3 + 2);
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(MethodInvocation.invoke(new MethodDescription.Latent(JavaType.RECORD.getTypeStub(), new MethodDescription.Token(Opcodes.ACC_PUBLIC))));
        int offset = 1;
        for (RecordComponentDescription.InDefinedShape recordComponent : instrumentedType.getRecordComponents()) {
            stackManipulations.add(MethodVariableAccess.loadThis());
            stackManipulations.add(MethodVariableAccess.of(recordComponent.getType()).loadFrom(offset));
            stackManipulations.add(FieldAccess.forField(instrumentedType.getDeclaredFields()
                    .filter(named(recordComponent.getActualName()))
                    .getOnly()).write());
            offset += recordComponent.getType().getStackSize().getSize();
        }
        stackManipulations.add(MethodReturn.VOID);
        return new Simple(stackManipulations).apply(methodVisitor, implementationContext, instrumentedMethod);
    }
}
 
Example #8
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplementationAppendingMethod() throws Exception {
    DynamicType.Loaded<MethodCallAppending> loaded = new ByteBuddy()
            .subclass(MethodCallAppending.class)
            .method(isDeclaredBy(MethodCallAppending.class))
            .intercept(MethodCall.invokeSuper().andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(MethodCallAppending.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallAppending instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallAppending.class)));
    assertThat(instance, instanceOf(MethodCallAppending.class));
    assertThat(instance.foo(), is((Object) FOO));
    instance.assertOnlyCall(FOO);
}
 
Example #9
Source File: PropertyMutatorCollector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext) {

    final boolean mustCast = (beanValueAccess == MethodVariableAccess.REFERENCE);

    final List<StackManipulation> operations = new ArrayList<StackManipulation>();
    operations.add(loadLocalVar()); // load local for cast bean
    operations.add(loadBeanValueArg());

    final AnnotatedMember member = prop.getMember();
    if (mustCast) {
        operations.add(TypeCasting.to(new ForLoadedType(getClassToCastBeanValueTo(member))));
    }

    operations.add(invocationOperation(member, beanClassDescription));
    operations.add(MethodReturn.VOID);

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example #10
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplementationAppendingConstructor() throws Exception {
    DynamicType.Loaded<MethodCallAppending> loaded = new ByteBuddy()
            .subclass(MethodCallAppending.class)
            .method(isDeclaredBy(MethodCallAppending.class))
            .intercept(MethodCall.construct(Object.class.getDeclaredConstructor())
                    .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(MethodCallAppending.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallAppending instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallAppending.class)));
    assertThat(instance, instanceOf(MethodCallAppending.class));
    assertThat(instance.foo(), is((Object) FOO));
    instance.assertZeroCalls();
}
 
Example #11
Source File: RedefinitionDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
public void testDefaultInterfaceSubInterface() throws Exception {
    Class<?> interfaceType = Class.forName(DEFAULT_METHOD_INTERFACE);
    Class<?> dynamicInterfaceType = new ByteBuddy()
            .redefine(interfaceType)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(BAR), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    Class<?> dynamicClassType = new ByteBuddy()
            .subclass(dynamicInterfaceType)
            .make()
            .load(dynamicInterfaceType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(dynamicClassType.getMethod(FOO).invoke(dynamicClassType.getDeclaredConstructor().newInstance()), is((Object) BAR));
    assertThat(dynamicInterfaceType.getDeclaredMethods().length, is(1));
    assertThat(dynamicClassType.getDeclaredMethods().length, is(0));
}
 
Example #12
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoredMethodDoesNotApplyForDefined() throws Exception {
    Class<?> type = createPlain()
            .ignoreAlso(named(FOO))
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #13
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBridgeMethodCreation() throws Exception {
    Class<?> dynamicType = create(BridgeRetention.Inner.class)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertEquals(String.class, dynamicType.getDeclaredMethod(FOO).getReturnType());
    assertThat(dynamicType.getDeclaredMethod(FOO).getGenericReturnType(), is((Type) String.class));
    BridgeRetention<String> bridgeRetention = (BridgeRetention<String>) dynamicType.getDeclaredConstructor().newInstance();
    assertThat(bridgeRetention.foo(), is(FOO));
    bridgeRetention.assertZeroCalls();
}
 
Example #14
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    MethodDescription.InDefinedShape proxyMethod = methodAccessorFactory.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    return new StackManipulation.Compound(
            MethodVariableAccess.loadThis(),
            fieldLoadingInstruction,
            MethodVariableAccess.allArgumentsOf(instrumentedMethod).asBridgeOf(proxyMethod),
            MethodInvocation.invoke(proxyMethod),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
}
 
Example #15
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Hash code method must not be static: " + instrumentedMethod);
    } else if (instrumentedMethod.getParameters().size() != 1 || instrumentedMethod.getParameters().getOnly().getType().isPrimitive()) {
        throw new IllegalStateException();
    } else if (!instrumentedMethod.getReturnType().represents(boolean.class)) {
        throw new IllegalStateException("Hash code method does not return primitive boolean: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(3 + fieldDescriptions.size() * 8);
    stackManipulations.add(baseline);
    int padding = 0;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        stackManipulations.add(MethodVariableAccess.REFERENCE.loadFrom(1));
        stackManipulations.add(TypeCasting.to(instrumentedType));
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        NullValueGuard nullValueGuard = fieldDescription.getType().isPrimitive() || fieldDescription.getType().isArray() || nonNullable.matches(fieldDescription)
                ? NullValueGuard.NoOp.INSTANCE
                : new NullValueGuard.UsingJump(instrumentedMethod);
        stackManipulations.add(nullValueGuard.before());
        stackManipulations.add(ValueComparator.of(fieldDescription.getType()));
        stackManipulations.add(nullValueGuard.after());
        padding = Math.max(padding, nullValueGuard.getRequiredVariablePadding());
    }
    stackManipulations.add(IntegerConstant.forValue(true));
    stackManipulations.add(MethodReturn.INTEGER);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize() + padding);
}
 
Example #16
Source File: SubclassDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBridgeMethodCreation() throws Exception {
    Class<?> dynamicType = new ByteBuddy()
            .subclass(BridgeRetention.Inner.class)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertEquals(String.class, dynamicType.getDeclaredMethod(FOO).getReturnType());
    assertThat(dynamicType.getDeclaredMethod(FOO).getGenericReturnType(), is((Type) String.class));
    BridgeRetention<String> bridgeRetention = (BridgeRetention<String>) dynamicType.getDeclaredConstructor().newInstance();
    assertThat(bridgeRetention.foo(), is(FOO));
    bridgeRetention.assertZeroCalls();
}
 
Example #17
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.getReturnType().isPrimitive()) {
        throw new IllegalStateException("Cannot return null from " + instrumentedMethod);
    }
    return new ByteCodeAppender.Simple(
            NullConstant.INSTANCE,
            MethodReturn.REFERENCE
    ).apply(methodVisitor, implementationContext, instrumentedMethod);
}
 
Example #18
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic() || !instrumentedType.isAssignableTo(instrumentedMethod.getReturnType().asErasure())) {
        throw new IllegalStateException("Cannot return 'this' from " + instrumentedMethod);
    }
    return new ByteCodeAppender.Simple(
            MethodVariableAccess.loadThis(),
            MethodReturn.REFERENCE
    ).apply(methodVisitor, implementationContext, instrumentedMethod);
}
 
Example #19
Source File: TypeWriterMethodPoolRecordTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkippedMethodCannotBePrepended() throws Exception {
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.OBJECT);
    assertThat(new TypeWriter.MethodPool.Record.ForNonImplementedMethod(methodDescription).prepend(byteCodeAppender), hasPrototype((TypeWriter.MethodPool.Record)
            new TypeWriter.MethodPool.Record.ForDefinedMethod.WithBody(methodDescription,
                    new ByteCodeAppender.Compound(byteCodeAppender, new ByteCodeAppender.Simple(DefaultValue.REFERENCE, MethodReturn.REFERENCE)))));
}
 
Example #20
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
    if (!instrumentedMethod.isMethod()) {
        throw new IllegalArgumentException(instrumentedMethod + " does not describe a field getter or setter");
    }
    FieldDescription fieldDescription = fieldLocation.resolve(instrumentedMethod);
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot set instance field " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation implementation, initialization = fieldDescription.isStatic()
            ? StackManipulation.Trivial.INSTANCE
            : MethodVariableAccess.loadThis();
    if (!instrumentedMethod.getReturnType().represents(void.class)) {
        implementation = new StackManipulation.Compound(
                initialization,
                FieldAccess.forField(fieldDescription).read(),
                assigner.assign(fieldDescription.getType(), instrumentedMethod.getReturnType(), typing),
                MethodReturn.of(instrumentedMethod.getReturnType())
        );
    } else if (instrumentedMethod.getReturnType().represents(void.class) && instrumentedMethod.getParameters().size() == 1) {
        if (fieldDescription.isFinal() && instrumentedMethod.isMethod()) {
            throw new IllegalStateException("Cannot set final field " + fieldDescription + " from " + instrumentedMethod);
        }
        implementation = new StackManipulation.Compound(
                initialization,
                MethodVariableAccess.load(instrumentedMethod.getParameters().get(0)),
                assigner.assign(instrumentedMethod.getParameters().get(0).getType(), fieldDescription.getType(), typing),
                FieldAccess.forField(fieldDescription).write(),
                MethodReturn.VOID
        );
    } else {
        throw new IllegalArgumentException("Method " + instrumentedMethod + " is no bean accessor");
    }
    if (!implementation.isValid()) {
        throw new IllegalStateException("Cannot set or get value of " + instrumentedMethod + " using " + fieldDescription);
    }
    return new Size(implementation.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #21
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodDefinition() throws Exception {
    Class<?> type = createPlain()
            .defineMethod(FOO, Object.class, Visibility.PUBLIC)
            .throwing(Exception.class)
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Method method = type.getDeclaredMethod(FOO);
    assertThat(method.getReturnType(), CoreMatchers.<Class<?>>is(Object.class));
    assertThat(method.getExceptionTypes(), is(new Class<?>[]{Exception.class}));
    assertThat(method.getModifiers(), is(Modifier.PUBLIC));
    assertThat(method.invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #22
Source File: MethodDelegationBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
public StackManipulation resolve(Assigner assigner, Assigner.Typing typing, MethodDescription source, MethodDescription target) {
    return new StackManipulation.Compound(assigner.assign(target.isConstructor()
                    ? target.getDeclaringType().asGenericType()
                    : target.getReturnType(),
            source.getReturnType(),
            typing), MethodReturn.of(source.getReturnType()));
}
 
Example #23
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoredMethod() throws Exception {
    Class<?> type = createPlain()
            .ignoreAlso(named(TO_STRING))
            .method(named(TO_STRING))
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredConstructor().newInstance().toString(), CoreMatchers.not(FOO));
}
 
Example #24
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext,
                  MethodDescription instrumentedMethod) {
    if (!instrumentedMethod.getReturnType().asErasure().represents(int.class)) {
        throw new IllegalArgumentException(instrumentedMethod + " must return int");
    }
    StackManipulation.Size operandStackSize = new StackManipulation.Compound(
            IntegerConstant.forValue(10),
            IntegerConstant.forValue(50),
            IntegerSum.INSTANCE,
            MethodReturn.INTEGER
    ).apply(methodVisitor, implementationContext);
    return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #25
Source File: MethodDelegationChainedTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testChainingVoid() throws Exception {
    VoidInterceptor voidInterceptor = new VoidInterceptor();
    DynamicType.Loaded<Foo> dynamicType = new ByteBuddy().subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .filter(isDeclaredBy(VoidInterceptor.class))
                    .to(voidInterceptor)
                    .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredConstructor().newInstance().foo(), is(FOO));
    assertThat(voidInterceptor.intercepted, is(true));
}
 
Example #26
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTransformationExistingMethod() throws Exception {
    Class<?> type = create(Transform.class)
            .method(named(FOO))
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .transform(Transformer.ForMethod.withModifiers(MethodManifestation.FINAL))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Method foo = type.getDeclaredMethod(FOO);
    assertThat(foo.invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
    assertThat(foo.getModifiers(), is(Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC));
}
 
Example #27
Source File: SuperMethodCallOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAndThen() throws Exception {
    DynamicType.Loaded<Foo> loaded = new ByteBuddy()
            .subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(SuperMethodCall.INSTANCE.andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    Foo foo = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(foo.foo(), is(FOO));
    foo.assertOnlyCall(FOO);
}
 
Example #28
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTransformation() throws Exception {
    Class<?> type = createPlain()
            .method(named(TO_STRING))
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .transform(Transformer.ForMethod.withModifiers(MethodManifestation.FINAL))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredConstructor().newInstance().toString(), is(FOO));
    assertThat(type.getDeclaredMethod(TO_STRING).getModifiers(), is(Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC));
}
 
Example #29
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorInvokingMethod() throws Exception {
    Class<?> type = createPlain()
            .defineMethod(FOO, Object.class, Visibility.PUBLIC)
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Method method = type.getDeclaredMethod(FOO);
    assertThat(method.invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #30
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationOrder() throws Exception {
    assertThat(createPlain()
            .method(named(TO_STRING)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .method(named(TO_STRING)).intercept(new Implementation.Simple(new TextConstant(BAR), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .toString(), is(BAR));
}