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

The following examples show how to use net.bytebuddy.implementation.bytecode.member.MethodInvocation. 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: RebaseImplementationTarget.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a special method invocation for the given method.
 *
 * @param resolvedMethod      The rebased method to be invoked.
 * @param instrumentedType    The instrumented type on which the method is to be invoked if it is non-static.
 * @param prependedParameters Any additional arguments that are to be provided to the rebased method.
 * @return A special method invocation of the rebased method.
 */
protected static Implementation.SpecialMethodInvocation of(MethodDescription resolvedMethod, TypeDescription instrumentedType, TypeList prependedParameters) {
    StackManipulation stackManipulation = resolvedMethod.isStatic()
            ? MethodInvocation.invoke(resolvedMethod)
            : MethodInvocation.invoke(resolvedMethod).special(instrumentedType);
    if (stackManipulation.isValid()) {
        List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(prependedParameters.size() + 1);
        for (TypeDescription prependedParameter : prependedParameters) {
            stackManipulations.add(DefaultValue.of(prependedParameter));
        }
        stackManipulations.add(stackManipulation);
        return new RebasedMethodInvocation(resolvedMethod, instrumentedType, new Compound(stackManipulations), prependedParameters);
    } else {
        return Illegal.INSTANCE;
    }
}
 
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: SerializedConstant.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    try {
        return new StackManipulation.Compound(
                TypeCreation.of(TypeDescription.ForLoadedType.of(ObjectInputStream.class)),
                Duplication.SINGLE,
                TypeCreation.of(TypeDescription.ForLoadedType.of(ByteArrayInputStream.class)),
                Duplication.SINGLE,
                new TextConstant(serialization),
                new TextConstant(CHARSET),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(String.class.getMethod("getBytes", String.class))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedConstructor(ByteArrayInputStream.class.getConstructor(byte[].class))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedConstructor(ObjectInputStream.class.getConstructor(InputStream.class))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ObjectInputStream.class.getMethod("readObject")))
        ).apply(methodVisitor, implementationContext);
    } catch (NoSuchMethodException exception) {
        throw new IllegalStateException("Could not locate Java API method", exception);
    }
}
 
Example #5
Source File: MethodConstant.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 auxiliaryType = implementationContext.register(PrivilegedMemberLookupAction.of(methodDescription));
    return new Compound(
            TypeCreation.of(auxiliaryType),
            Duplication.SINGLE,
            ClassConstant.of(methodDescription.getDeclaringType()),
            methodName,
            ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
                    .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())),
            MethodInvocation.invoke(auxiliaryType.getDeclaredMethods().filter(isConstructor()).getOnly()),
            MethodInvocation.invoke(DO_PRIVILEGED),
            TypeCasting.to(TypeDescription.ForLoadedType.of(methodDescription.isConstructor()
                    ? Constructor.class
                    : Method.class))
    ).apply(methodVisitor, implementationContext);
}
 
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.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 #7
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 #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
@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 #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 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 #12
Source File: ExceptionMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation make() {
    return new StackManipulation.Compound(
            TypeCreation.of(throwableType),
            Duplication.SINGLE,
            MethodInvocation.invoke(targetConstructor));
}
 
Example #13
Source File: ExceptionMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation make() {
    return new StackManipulation.Compound(
            TypeCreation.of(throwableType),
            Duplication.SINGLE,
            new TextConstant(message),
            MethodInvocation.invoke(targetConstructor));
}
 
Example #14
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a type definition to a equality comparison.
 *
 * @param typeDefinition The type definition to resolve.
 * @return The stack manipulation to apply.
 */
public static StackManipulation of(TypeDefinition typeDefinition) {
    if (typeDefinition.represents(boolean.class)
            || typeDefinition.represents(byte.class)
            || typeDefinition.represents(short.class)
            || typeDefinition.represents(char.class)
            || typeDefinition.represents(int.class)) {
        return ConditionalReturn.onNonEqualInteger();
    } else if (typeDefinition.represents(long.class)) {
        return new Compound(LONG, ConditionalReturn.onNonZeroInteger());
    } else if (typeDefinition.represents(float.class)) {
        return new Compound(FLOAT, ConditionalReturn.onNonZeroInteger());
    } else if (typeDefinition.represents(double.class)) {
        return new Compound(DOUBLE, ConditionalReturn.onNonZeroInteger());
    } else if (typeDefinition.represents(boolean[].class)) {
        return new Compound(BOOLEAN_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(byte[].class)) {
        return new Compound(BYTE_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(short[].class)) {
        return new Compound(SHORT_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(char[].class)) {
        return new Compound(CHARACTER_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(int[].class)) {
        return new Compound(INTEGER_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(long[].class)) {
        return new Compound(LONG_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(float[].class)) {
        return new Compound(FLOAT_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(double[].class)) {
        return new Compound(DOUBLE_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.isArray()) {
        return new Compound(typeDefinition.getComponentType().isArray()
                ? NESTED_ARRAY
                : REFERENCE_ARRAY, ConditionalReturn.onZeroInteger());
    } else {
        return new Compound(MethodInvocation.invoke(EQUALS).virtual(typeDefinition.asErasure()), ConditionalReturn.onZeroInteger());
    }
}
 
Example #15
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
public StackManipulation resolve(TypeDescription instrumentedType) {
    return new StackManipulation.Compound(
            MethodVariableAccess.REFERENCE.loadFrom(1),
            ConditionalReturn.onNullValue(),
            MethodVariableAccess.REFERENCE.loadFrom(0),
            MethodInvocation.invoke(GET_CLASS),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            MethodInvocation.invoke(GET_CLASS),
            ConditionalReturn.onNonIdentity()
    );
}
 
Example #16
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
protected StackManipulation resolve(TypeDescription instrumentedType) {
    TypeDefinition superClass = instrumentedType.getSuperClass();
    if (superClass == null) {
        throw new IllegalStateException(instrumentedType + " does not declare a super class");
    }
    return new StackManipulation.Compound(MethodVariableAccess.loadThis(),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            MethodInvocation.invoke(EQUALS).special(superClass.asErasure()),
            ConditionalReturn.onZeroInteger());
}
 
Example #17
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 #18
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 #19
Source File: InvokeDynamic.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) {
    InvocationProvider.Target.Resolved target = invocationProvider.make(instrumentedMethod).resolve(instrumentedType, assigner, typing);
    StackManipulation.Size size = new StackManipulation.Compound(
            target.getStackManipulation(),
            MethodInvocation.invoke(bootstrap).dynamic(target.getInternalName(),
                    target.getReturnType(),
                    target.getParameterTypes(),
                    arguments),
            terminationHandler.resolve(instrumentedMethod, target.getReturnType(), assigner, typing)
    ).apply(methodVisitor, implementationContext);
    return new Size(size.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #20
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the singleton instance.
 */
@SuppressFBWarnings(value = "SE_BAD_FIELD_STORE", justification = "Fields of enumerations are never serialized")
AbstractMethodErrorThrow() {
    TypeDescription abstractMethodError = TypeDescription.ForLoadedType.of(AbstractMethodError.class);
    MethodDescription constructor = abstractMethodError.getDeclaredMethods()
            .filter(isConstructor().and(takesArguments(0))).getOnly();
    implementation = new Compound(TypeCreation.of(abstractMethodError),
            Duplication.SINGLE,
            MethodInvocation.invoke(constructor),
            Throw.INSTANCE);
}
 
Example #21
Source File: MethodCallProxy.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 auxiliaryType = implementationContext
            .register(new MethodCallProxy(specialMethodInvocation, serializable));
    return new Compound(
            TypeCreation.of(auxiliaryType),
            Duplication.SINGLE,
            MethodVariableAccess.allArgumentsOf(specialMethodInvocation.getMethodDescription()).prependThisReference(),
            MethodInvocation.invoke(auxiliaryType.getDeclaredMethods().filter(isConstructor()).getOnly())
    ).apply(methodVisitor, implementationContext);
}
 
Example #22
Source File: NexusAccessor.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) {
    try {
        return new ByteCodeAppender.Simple(new StackManipulation.Compound(
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ClassLoader.class.getMethod("getSystemClassLoader"))),
                new TextConstant(Nexus.class.getName()),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ClassLoader.class.getMethod("loadClass", String.class))),
                new TextConstant("initialize"),
                ArrayFactory.forType(TypeDescription.Generic.CLASS)
                        .withValues(Arrays.asList(
                                ClassConstant.of(TypeDescription.CLASS),
                                ClassConstant.of(TypeDescription.ForLoadedType.of(int.class)))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Class.class.getMethod("getMethod", String.class, Class[].class))),
                NullConstant.INSTANCE,
                ArrayFactory.forType(TypeDescription.Generic.OBJECT)
                        .withValues(Arrays.asList(
                                ClassConstant.of(instrumentedMethod.getDeclaringType().asErasure()),
                                new StackManipulation.Compound(
                                        IntegerConstant.forValue(identification),
                                        MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Integer.class.getMethod("valueOf", int.class)))))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Method.class.getMethod("invoke", Object.class, Object[].class))),
                Removal.SINGLE
        )).apply(methodVisitor, implementationContext, instrumentedMethod);
    } catch (NoSuchMethodException exception) {
        throw new IllegalStateException("Cannot locate method", exception);
    }
}
 
Example #23
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public StackManipulation assign(TypeDescription.Generic source, TypeDescription.Generic target, Typing typing) {
    if (!source.isPrimitive() && target.represents(String.class)) {
        MethodDescription toStringMethod = TypeDescription.OBJECT.getDeclaredMethods()
                .filter(named("toString"))
                .getOnly();
        return MethodInvocation.invoke(toStringMethod).virtual(source.asErasure());
    } else {
        return StackManipulation.Illegal.INSTANCE;
    }
}
 
Example #24
Source File: MethodConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    return new Compound(
            ClassConstant.of(methodDescription.getDeclaringType()),
            methodName(),
            ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
                    .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())),
            MethodInvocation.invoke(accessorMethod())
    ).apply(methodVisitor, implementationContext);
}
 
Example #25
Source File: HashCodeMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a type definition to a hash code.
 *
 * @param typeDefinition The type definition to resolve.
 * @return The stack manipulation to apply.
 */
public static StackManipulation of(TypeDefinition typeDefinition) {
    if (typeDefinition.represents(boolean.class)
            || typeDefinition.represents(byte.class)
            || typeDefinition.represents(short.class)
            || typeDefinition.represents(char.class)
            || typeDefinition.represents(int.class)) {
        return Trivial.INSTANCE;
    } else if (typeDefinition.represents(long.class)) {
        return LONG;
    } else if (typeDefinition.represents(float.class)) {
        return FLOAT;
    } else if (typeDefinition.represents(double.class)) {
        return DOUBLE;
    } else if (typeDefinition.represents(boolean[].class)) {
        return BOOLEAN_ARRAY;
    } else if (typeDefinition.represents(byte[].class)) {
        return BYTE_ARRAY;
    } else if (typeDefinition.represents(short[].class)) {
        return SHORT_ARRAY;
    } else if (typeDefinition.represents(char[].class)) {
        return CHARACTER_ARRAY;
    } else if (typeDefinition.represents(int[].class)) {
        return INTEGER_ARRAY;
    } else if (typeDefinition.represents(long[].class)) {
        return LONG_ARRAY;
    } else if (typeDefinition.represents(float[].class)) {
        return FLOAT_ARRAY;
    } else if (typeDefinition.represents(double[].class)) {
        return DOUBLE_ARRAY;
    } else if (typeDefinition.isArray()) {
        return typeDefinition.getComponentType().isArray()
                ? NESTED_ARRAY
                : REFERENCE_ARRAY;
    } else {
        return MethodInvocation.invoke(HASH_CODE).virtual(typeDefinition.asErasure());
    }
}
 
Example #26
Source File: HashCodeMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation resolve(TypeDescription instrumentedType) {
    TypeDefinition superClass = instrumentedType.getSuperClass();
    if (superClass == null) {
        throw new IllegalStateException(instrumentedType + " does not declare a super class");
    }
    return new StackManipulation.Compound(MethodVariableAccess.loadThis(), MethodInvocation.invoke(HASH_CODE).special(superClass.asErasure()));
}
 
Example #27
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 #28
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(MethodDescription invokedMethod, Implementation.Target implementationTarget) {
    if (!invokedMethod.isAccessibleTo(implementationTarget.getInstrumentedType()) || !invokedMethod.isVirtual()) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " virtually");
    }
    return MethodInvocation.invoke(invokedMethod);
}
 
Example #29
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(MethodDescription invokedMethod, Implementation.Target implementationTarget) {
    if (!invokedMethod.isInvokableOn(typeDescription)) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + typeDescription);
    }
    return MethodInvocation.invoke(invokedMethod).virtual(typeDescription);
}
 
Example #30
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(MethodDescription invokedMethod, Implementation.Target implementationTarget) {
    if (invokedMethod.isVirtual() && !invokedMethod.isInvokableOn(instrumentedType)) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + instrumentedType);
    }
    return invokedMethod.isVirtual()
            ? MethodInvocation.invoke(invokedMethod).virtual(instrumentedType)
            : MethodInvocation.invoke(invokedMethod);
}