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

The following examples show how to use net.bytebuddy.implementation.bytecode.member.FieldAccess. 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: FieldAccessor.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) {
    FieldDescription fieldDescription = fieldLocation.resolve(instrumentedMethod);
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot set instance field " + fieldDescription + " from " + instrumentedMethod);
    } else if (fieldDescription.isFinal() && instrumentedMethod.isMethod()) {
        throw new IllegalStateException("Cannot set final field " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation stackManipulation = resolve(initialized, fieldDescription, instrumentedType, instrumentedMethod);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Set value cannot be assigned to " + fieldDescription);
    }
    return new Size(new StackManipulation.Compound(
            instrumentedMethod.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            stackManipulation,
            FieldAccess.forField(fieldDescription).write(),
            terminationHandler.resolve(instrumentedMethod)
    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
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: TypeProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription proxyType = implementationContext
            .register(new TypeProxy(proxiedType,
                    implementationTarget,
                    InvocationFactory.Default.SUPER_METHOD,
                    ignoreFinalizer,
                    serializableProxy));
    StackManipulation[] constructorValue = new StackManipulation[constructorParameters.size()];
    int index = 0;
    for (TypeDescription parameterType : constructorParameters) {
        constructorValue[index++] = DefaultValue.of(parameterType);
    }
    return new Compound(
            TypeCreation.of(proxyType),
            Duplication.SINGLE,
            new Compound(constructorValue),
            MethodInvocation.invoke(proxyType.getDeclaredMethods().filter(isConstructor().and(takesArguments(constructorParameters))).getOnly()),
            Duplication.SINGLE,
            MethodVariableAccess.loadThis(),
            FieldAccess.forField(proxyType.getDeclaredFields().filter((named(INSTANCE_FIELD))).getOnly()).write()
    ).apply(methodVisitor, implementationContext);
}
 
Example #5
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot access non-static " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation stackManipulation = new StackManipulation.Compound(
            fieldDescription.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            FieldAccess.forField(fieldDescription).read(),
            assigner.assign(fieldDescription.getType(), target.getType(), typing)
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + target);
    }
    return stackManipulation;
}
 
Example #6
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription proxyType = implementationContext.register(new TypeProxy(proxiedType,
            implementationTarget,
            InvocationFactory.Default.DEFAULT_METHOD,
            true,
            serializableProxy));
    return new Compound(
            TypeCreation.of(proxyType),
            Duplication.SINGLE,
            MethodInvocation.invoke(proxyType.getDeclaredMethods().filter(isConstructor()).getOnly()),
            Duplication.SINGLE,
            MethodVariableAccess.loadThis(),
            FieldAccess.forField(proxyType.getDeclaredFields().filter((named(INSTANCE_FIELD))).getOnly()).write()
    ).apply(methodVisitor, implementationContext);
}
 
Example #7
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected StackManipulation resolve(FieldLocation.Prepared target,
                                    FieldDescription fieldDescription,
                                    TypeDescription instrumentedType,
                                    MethodDescription instrumentedMethod) {
    FieldDescription resolved = target.resolve(instrumentedMethod);
    if (!resolved.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot set instance field " + fieldDescription + " from " + instrumentedMethod);
    }
    return new StackManipulation.Compound(
            resolved.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            FieldAccess.forField(resolved).read(),
            assigner.assign(resolved.getType(), fieldDescription.getType(), typing)
    );
}
 
Example #8
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 #9
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 #10
Source File: PropertyMutatorCollector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected StackManipulation invocationOperation(AnnotatedMember annotatedMember,
        TypeDefinition beanClassDescription) {

    final String fieldName = annotatedMember.getName();
    final FieldList<FieldDescription> matchingFields =
            (FieldList<FieldDescription>) beanClassDescription.getDeclaredFields().filter(named(fieldName));

    if (matchingFields.size() == 1) { //method was declared on class
        return FieldAccess.forField(matchingFields.getOnly()).write();
    }
    if (matchingFields.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 field: " + fieldName);
    }
}
 
Example #11
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 fieldName = annotatedMember.getName();
    @SuppressWarnings("unchecked")
    final FieldList<FieldDescription> matchingFields =
            (FieldList<FieldDescription>) beanClassDescription.getDeclaredFields().filter(named(fieldName));

    if (matchingFields.size() == 1) { //method was declared on class
        return FieldAccess.forField(matchingFields.getOnly()).read();
    }
    if (matchingFields.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 field: " + fieldName);
    }
}
 
Example #12
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitTypeInitializer() throws Exception {
    assertThat(createPlain()
            .defineField(FOO, String.class, Ownership.STATIC, Visibility.PUBLIC)
            .initializer(new ByteCodeAppender() {
                public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
                    return new Size(new StackManipulation.Compound(
                            new TextConstant(FOO),
                            FieldAccess.forField(instrumentedMethod.getDeclaringType().getDeclaredFields().filter(named(FOO)).getOnly()).write()
                    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
                }
            }).make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredField(FOO)
            .get(null), is((Object) FOO));
}
 
Example #13
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Resolved resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Assigner.Typing typing) {
    FieldDescription fieldDescription = instrumentedType.getDeclaredFields().filter(named(name)).getOnly();
    StackManipulation stackManipulation = assigner.assign(fieldDescription.getType(), fieldType.asGenericType(), typing);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + fieldType);
    }
    return new Resolved.Simple(new StackManipulation.Compound(FieldAccess.forField(fieldDescription).read(),
            stackManipulation), fieldDescription.getType().asErasure());
}
 
Example #14
Source File: HashCodeMethod.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.getReturnType().represents(int.class)) {
        throw new IllegalStateException("Hash code method does not return primitive integer: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(2 + fieldDescriptions.size() * 8);
    stackManipulations.add(initialValue);
    int padding = 0;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        stackManipulations.add(IntegerConstant.forValue(multiplier));
        stackManipulations.add(Multiplication.INTEGER);
        stackManipulations.add(MethodVariableAccess.loadThis());
        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(ValueTransformer.of(fieldDescription.getType()));
        stackManipulations.add(Addition.INTEGER);
        stackManipulations.add(nullValueGuard.after());
        padding = Math.max(padding, nullValueGuard.getRequiredVariablePadding());
    }
    stackManipulations.add(MethodReturn.INTEGER);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize() + padding);
}
 
Example #15
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Resolved resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Assigner.Typing typing) {
    FieldLocator.Resolution resolution = fieldLocatorFactory.make(instrumentedType).locate(fieldName);
    if (!resolution.isResolved()) {
        throw new IllegalStateException("Cannot find a field " + fieldName + " for " + instrumentedType);
    } else if (!resolution.getField().isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot access non-static " + resolution.getField() + " from " + instrumentedMethod);
    }
    return doResolve(new StackManipulation.Compound(resolution.getField().isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(), FieldAccess.forField(resolution.getField()).read()),
            resolution.getField().getType(),
            assigner,
            typing);
}
 
Example #16
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected StackManipulation resolve(FieldDescription.InDefinedShape target,
                                    FieldDescription fieldDescription,
                                    TypeDescription instrumentedType,
                                    MethodDescription instrumentedMethod) {
    if (fieldDescription.isFinal() && instrumentedMethod.isMethod()) {
        throw new IllegalArgumentException("Cannot set final field " + fieldDescription + " from " + instrumentedMethod);
    }
    return new StackManipulation.Compound(
            FieldAccess.forField(target).read(),
            assigner.assign(TypeDescription.ForLoadedType.of(value.getClass()).asGenericType(), fieldDescription.getType(), typing)
    );
}
 
Example #17
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 #18
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 #19
Source File: SuperMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    StackManipulation methodConstant = privileged
            ? MethodConstant.ofPrivileged(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC))
            : MethodConstant.of(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC));
    return (cached
            ? FieldAccess.forField(implementationContext.cache(methodConstant, TypeDescription.ForLoadedType.of(Method.class))).read()
            : methodConstant).apply(methodVisitor, implementationContext);
}
 
Example #20
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) {
    TypeDescription proxyType = implementationContext.register(new TypeProxy(proxiedType,
            implementationTarget,
            InvocationFactory.Default.SUPER_METHOD,
            ignoreFinalizer,
            serializableProxy));
    return new Compound(
            MethodInvocation.invoke(proxyType.getDeclaredMethods().filter(named(REFLECTION_METHOD).and(takesArguments(0))).getOnly()),
            Duplication.SINGLE,
            MethodVariableAccess.loadThis(),
            FieldAccess.forField(proxyType.getDeclaredFields().filter((named(INSTANCE_FIELD))).getOnly()).write()
    ).apply(methodVisitor, implementationContext);
}
 
Example #21
Source File: DefaultMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    StackManipulation methodConstant = privileged
            ? MethodConstant.ofPrivileged(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC))
            : MethodConstant.of(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC));
    return (cached
            ? FieldAccess.forField(implementationContext.cache(methodConstant, TypeDescription.ForLoadedType.of(Method.class))).read()
            : methodConstant).apply(methodVisitor, implementationContext);
}
 
Example #22
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Defines the given enumeration values to be provided as arguments to the invoked method where the values
 * are read from the enumeration class on demand.
 *
 * @param enumerationDescription The enumeration descriptions to provide as arguments.
 * @return A method call that hands the provided arguments to the invoked method.
 */
public MethodCall with(EnumerationDescription... enumerationDescription) {
    List<ArgumentLoader.Factory> argumentLoaders = new ArrayList<ArgumentLoader.Factory>(enumerationDescription.length);
    for (EnumerationDescription anEnumerationDescription : enumerationDescription) {
        argumentLoaders.add(new ArgumentLoader.ForStackManipulation(FieldAccess.forEnumeration(anEnumerationDescription), anEnumerationDescription.getEnumerationType()));
    }
    return with(argumentLoaders);
}
 
Example #23
Source File: SetSerializedFieldName.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public Size apply(
    MethodVisitor methodVisitor,
    Context implementationContext,
    MethodDescription instrumentedMethod) {
  Map<String, FieldDescription> fieldsByName = CodeGenUtil.fieldsByName(implementationContext);
  StackManipulation.Size operandStackSize =
      new StackManipulation.Compound(
              new TextConstant(unserializedFieldValue),
              SerializeSupport_serializeString,
              FieldAccess.forField(fieldsByName.get(fieldName)).write())
          .apply(methodVisitor, implementationContext);
  return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #24
Source File: ByteBuddy.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) {
    FieldDescription valuesField = instrumentedType.getDeclaredFields().filter(named(ENUM_VALUES)).getOnly();
    MethodDescription cloneMethod = TypeDescription.Generic.OBJECT.getDeclaredMethods().filter(named(CLONE_METHOD_NAME)).getOnly();
    return new Size(new StackManipulation.Compound(
            FieldAccess.forField(valuesField).read(),
            MethodInvocation.invoke(cloneMethod).virtual(valuesField.getType().asErasure()),
            TypeCasting.to(valuesField.getType().asErasure()),
            MethodReturn.REFERENCE
    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #25
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation resolve(TypeDescription targetType,
                                 ByteCodeElement target,
                                 TypeList.Generic parameters,
                                 TypeDescription.Generic result,
                                 int freeOffset) {
    FieldDescription fieldDescription = fieldResolver.resolve(targetType, target, parameters, result);
    if (!fieldDescription.isAccessibleTo(instrumentedType)) {
        throw new IllegalStateException(instrumentedType + " cannot access " + fieldDescription);
    } else if (result.represents(void.class)) {
        if (parameters.size() != (fieldDescription.isStatic() ? 1 : 2)) {
            throw new IllegalStateException("Cannot set " + fieldDescription + " with " + parameters);
        } else if (!fieldDescription.isStatic() && !parameters.get(0).asErasure().isAssignableTo(fieldDescription.getDeclaringType().asErasure())) {
            throw new IllegalStateException("Cannot set " + fieldDescription + " on " + parameters.get(0));
        } else if (!parameters.get(fieldDescription.isStatic() ? 0 : 1).asErasure().isAssignableTo(fieldDescription.getType().asErasure())) {
            throw new IllegalStateException("Cannot set " + fieldDescription + " to " + parameters.get(fieldDescription.isStatic() ? 0 : 1));
        }
        return FieldAccess.forField(fieldDescription).write();
    } else {
        if (parameters.size() != (fieldDescription.isStatic() ? 0 : 1)) {
            throw new IllegalStateException("Cannot set " + fieldDescription + " with " + parameters);
        } else if (!fieldDescription.isStatic() && !parameters.get(0).asErasure().isAssignableTo(fieldDescription.getDeclaringType().asErasure())) {
            throw new IllegalStateException("Cannot get " + fieldDescription + " on " + parameters.get(0));
        } else if (!fieldDescription.getType().asErasure().isAssignableTo(result.asErasure())) {
            throw new IllegalStateException("Cannot get " + fieldDescription + " as " + result);
        }
        return FieldAccess.forField(fieldDescription).read();
    }
}
 
Example #26
Source File: Implementation.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) {
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            fieldDescription.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            FieldAccess.forField(fieldDescription).read(),
            MethodReturn.of(fieldDescription.getType())
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #27
Source File: Implementation.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) {
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            MethodVariableAccess.allArgumentsOf(instrumentedMethod).prependThisReference(),
            FieldAccess.forField(fieldDescription).write(),
            MethodReturn.VOID
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #28
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation prepare(MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic() && !fieldDescription.isStatic()) {
        throw new IllegalStateException("Cannot read " + fieldDescription + " from " + instrumentedMethod);
    }
    return new StackManipulation.Compound(fieldDescription.isStatic()
            ? StackManipulation.Trivial.INSTANCE
            : MethodVariableAccess.loadThis(), FieldAccess.forField(fieldDescription).read());
}
 
Example #29
Source File: ToStringMethod.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("toString method must not be static: " + instrumentedMethod);
    } else if (!instrumentedMethod.getReturnType().asErasure().isAssignableFrom(String.class)) {
        throw new IllegalStateException("toString method does not return String-compatible type: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(Math.max(0, fieldDescriptions.size() * 7 - 2) + 10);
    stackManipulations.add(TypeCreation.of(TypeDescription.ForLoadedType.of(StringBuilder.class)));
    stackManipulations.add(Duplication.SINGLE);
    stackManipulations.add(new TextConstant(prefix));
    stackManipulations.add(MethodInvocation.invoke(STRING_BUILDER_CONSTRUCTOR));
    stackManipulations.add(new TextConstant(start));
    stackManipulations.add(ValueConsumer.STRING);
    boolean first = true;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        if (first) {
            first = false;
        } else {
            stackManipulations.add(new TextConstant(separator));
            stackManipulations.add(ValueConsumer.STRING);
        }
        stackManipulations.add(new TextConstant(fieldDescription.getName() + definer));
        stackManipulations.add(ValueConsumer.STRING);
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        stackManipulations.add(ValueConsumer.of(fieldDescription.getType().asErasure()));
    }
    stackManipulations.add(new TextConstant(end));
    stackManipulations.add(ValueConsumer.STRING);
    stackManipulations.add(MethodInvocation.invoke(TO_STRING));
    stackManipulations.add(MethodReturn.REFERENCE);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #30
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    StackManipulation stackManipulation = new StackManipulation.Compound(
            FieldAccess.forField(fieldDescription).read(),
            assigner.assign(fieldDescription.getType(), target.getType(), typing));
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + fieldDescription.getType() + " to " + target);
    }
    return stackManipulation;
}