Top Description Inners Fields Constructors Methods
net.bytebuddy.asm

public Class Advice

extends Object
implements MethodVisitorWrapper, Implementation
Class Inheritance
All Implemented Interfaces
net.bytebuddy.implementation.Implementation, net.bytebuddy.dynamic.scaffold.InstrumentedType.Prepareable, net.bytebuddy.asm.AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper
Annotations
@Enhance
Imports
edu.umd.cs.findbugs.annotations.SuppressFBWarnings, net.bytebuddy.ClassFileVersion, net.bytebuddy.build.HashCodeAndEqualsPlugin, .RepeatedAnnotationPlugin, net.bytebuddy.description.annotation.AnnotationDescription, .AnnotationValue, net.bytebuddy.description.enumeration.EnumerationDescription, net.bytebuddy.description.field.FieldDescription, net.bytebuddy.description.method.MethodDescription, .MethodList, .ParameterDescription, .ParameterList, net.bytebuddy.description.type.TypeDefinition, .TypeDescription, .TypeList, .TypeVariableToken, net.bytebuddy.dynamic.ClassFileLocator, .TargetType, net.bytebuddy.dynamic.scaffold.FieldLocator, .InstrumentedType, .MethodGraph, net.bytebuddy.implementation.FieldAccessor, .Implementation, .SuperMethodCall, net.bytebuddy.implementation.bytecode.Addition, .ByteCodeAppender, .Duplication, .Removal, .StackManipulation, .StackSize, .Throw, net.bytebuddy.implementation.bytecode.assign.Assigner, net.bytebuddy.implementation.bytecode.collection.ArrayAccess, .ArrayFactory, net.bytebuddy.implementation.bytecode.constant.ClassConstant, .DefaultValue, .IntegerConstant, .MethodConstant, .NullConstant, .SerializedConstant, net.bytebuddy.implementation.bytecode.member.FieldAccess, .MethodInvocation, .MethodVariableAccess, net.bytebuddy.matcher.ElementMatcher, net.bytebuddy.pool.TypePool, net.bytebuddy.utility.CompoundList, .ConstantValue, .JavaConstant, .JavaType, .OpenedClassReader, net.bytebuddy.utility.nullability.AlwaysNull, .MaybeNull, net.bytebuddy.utility.visitor.ExceptionTableSensitiveMethodVisitor, .LineNumberPrependingMethodVisitor, .StackAwareMethodVisitor, net.bytebuddy.jar.asm.AnnotationVisitor, .Attribute, .ClassReader, .ClassVisitor, .ClassWriter, .Label, .MethodVisitor, .Opcodes, .Type, .TypePath, java.io.IOException, .Serializable, java.lang.annotation.Annotation, .Documented, .ElementType, .Retention, .RetentionPolicy, java.lang.reflect.Constructor, .Field, .Method, java.util.ArrayList, .Arrays, .Collection, .Collections, .HashMap, .IdentityHashMap, .LinkedHashMap, .List, .Map, .SortedMap, .TreeMap

Advice wrappers copy the code of blueprint methods to be executed before and/or after a matched method. To achieve this, a static method of a class is annotated by OnMethodEnter and/or OnMethodExit and provided to an instance of this class.

A method that is annotated with OnMethodEnter can annotate its parameters with Argument where field access to this parameter is substituted with access to the specified argument of the instrumented method. Alternatively, a parameter can be annotated by This where the this reference of the instrumented method is read when the parameter is accessed. This mechanism can also be used to assign a new value to the this reference of an instrumented method. If no annotation is used on a parameter, it is assigned the n-th parameter of the instrumented method for the n-th parameter of the advice method. All parameters must declare the exact same type as the parameters of the instrumented type or the method's declaring type for the This reference respectively if they are not marked as read-only. In the latter case, it suffices that a parameter type is a super type of the corresponding type of the instrumented method.

A method that is annotated with OnMethodExit can equally annotate its parameters with Argument and This. Additionally, it can annotate a parameter with Return to receive the original method's return value. By reassigning the return value, it is possible to replace the returned value. If an instrumented method does not return a value, this annotation must not be used. If a method returns exceptionally, the parameter is set to its default value, i.e. to 0 for primitive types and to null for reference types. The parameter's type must be equal to the instrumented method's return type if it is not set to read-only where it suffices to declare the parameter type to be of any super type to the instrumented method's return type. An exception can be read by annotating a parameter of type Throwable annotated with Thrown which is assigned the thrown Throwable or null if a method returns normally. Doing so, it is possible to exchange a thrown exception with any checked or unchecked exception.Finally, if a method annotated with OnMethodEnter exists and this method returns a value, this value can be accessed by a parameter annotated with Enter. This parameter must declare the same type as type being returned by the method annotated with OnMethodEnter. If the parameter is marked to be read-only, it suffices that the annotated parameter is of a super type of the return type of the method annotated by OnMethodEnter. If no such method exists or this method returns void, no such parameter must be declared. Any return value of a method that is annotated by OnMethodExit is discarded.

If any advice method throws an exception, the method is terminated prematurely. If the method annotated by OnMethodEnter throws an exception, the method annotated by OnMethodExit method is not invoked. If the instrumented method throws an exception, the method that is annotated by OnMethodExit is only invoked if the OnMethodExit#onThrowable() property is set to true what is the default. If this property is set to false, the Thrown annotation must not be used on any parameter.

Byte Buddy does not assert the visibility of any types that are referenced within an inlined advice method. It is the responsibility of the user of this class to assure that all types referenced within the advice methods are visible to the instrumented class. Failing to do so results in a IllegalAccessError at the instrumented class's runtime.

Advice can be used either as a AsmVisitorWrapper where any declared methods of the currently instrumented type are enhanced without replacing an existing implementation. Alternatively, advice can function as an Implementation where, by default, the original super or default method of the instrumented method is invoked. If this is not possible or undesired, the delegate implementation can be changed by specifying a wrapped implementation explicitly by Advice#wrap(Implementation).

When using an advice class as a visitor wrapper, native or abstract methods which are silently skipped when advice matches such a method.

Important Note

Since Java 6, class files contain stack map frames embedded into a method's byte code. When advice methods are compiled with a class file version less then Java 6 but are used for a class file that was compiled to Java 6 or newer, these stack map frames must be computed by ASM by using the ClassWriter#COMPUTE_FRAMES option. If the advice methods do not contain any branching instructions, this is not required. No action is required if the advice methods are at least compiled with Java 6 but are used on classes older than Java 6. This limitation only applies to advice methods that are inlined. Also, it is the responsibility of this class's user to assure that the advice method does not contain byte code constructs that are not supported by the class containing the instrumented method. In particular, pre Java-5 try-finally blocks cannot be inlined into classes with newer byte code levels as the jsr instruction was deprecated. Also, classes prior to Java 7 do not support the invokedynamic command which must not be contained by an advice method if the instrumented method targets an older class file format version.

Note

For the purpose of inlining, Java 5 and Java 6 byte code can be seen as the best candidate for advice methods. These versions do no longer allow subroutines, neither do they already allow invokedynamic instructions or method handles. This way, Java 5 and Java 6 byte code is compatible to both older and newer versions. One exception for backwards-incompatible byte code is the possibility to load type references from the constant pool onto the operand stack. These instructions can however easily be transformed for classes compiled to Java 4 and older by registering a TypeConstantAdjustment before the advice visitor.

Note

It is not possible to trigger break points in inlined advice methods as the debugging information of the inlined advice is not preserved. It is not possible in Java to reference more than one source file per class what makes translating such debugging information impossible. It is however possible to set break points in advice methods when invoking the original advice target. This allows debugging of advice code within unit tests that invoke the advice method without instrumentation. As a consequence of not transferring debugging information, the names of the parameters of an advice method do not matter when inlining, neither does any meta information on the advice method's body such as annotations or parameter modifiers.

Note

The behavior of this component is undefined if it is supplied with invalid byte code what might result in runtime exceptions.

Note

When using advice from a Java agent with an net.bytebuddy.agent.builder.AgentBuilder, it often makes sense to not include any library-specific code in the agent's jar file. For being able to locate the advice code in the context of the library dependencies, Byte Buddy offers an net.bytebuddy.agent.builder.AgentBuilder.Transformer.ForAdvice implementation that allows registering the agent's class file locators for assembly of the advice class's description at runtime and with respect to the specific user dependencies.

See Also
OnMethodEnter, OnMethodExit

Nested and Inner Type Summary

Modifier and TypeClass and Description
protected abstract static class
Advice.AdviceVisitor

A method visitor that weaves the advice methods' byte codes.

public static @interface
Advice.AllArguments

Assigns an array containing all arguments of the instrumented method to the annotated parameter.

protected static class
Advice.Appender

A byte code appender for implementing Advice.

public static @interface
Advice.Argument

Indicates that the annotated parameter should be mapped to the parameter with index Argument#value() of the instrumented method.

public static interface
Advice.ArgumentHandler

An argument handler is responsible for resolving offsets of the local variable array in the context of the applied instrumentation.

public abstract static class
Advice.AssignReturned

A post processor that uses the return value of an advice method to define values for fields, arguments, the instrumented method's return value or the exception being thrown.

public static interface
Advice.BootstrapArgumentResolver

A resolver for the arguments that are provided to a bootstrap method if dynamic dispatch is used.

protected static interface
Advice.Delegator

Materializes an advice invocation within a delegation.

protected static interface
Advice.Dispatcher

A dispatcher for implementing advice.

public static @interface
Advice.Enter

Indicates that the annotated parameter should be mapped to the value that is returned by the advice method that is annotated by OnMethodEnter.

public static interface
Advice.ExceptionHandler

An exception handler is responsible for providing byte code for handling an exception thrown from a suppressing advice method.

public static @interface
Advice.Exit

Indicates that the annotated parameter should be mapped to the value that is returned by the advice method that is annotated by OnMethodExit.

public static @interface
Advice.FieldGetterHandle

Indicates that the annotated parameter should be mapped to a java.lang.invoke.MethodHandle representing a field getter.

public static @interface
Advice.FieldSetterHandle

Indicates that the annotated parameter should be mapped to a java.lang.invoke.MethodHandle representing a field setter.

public static @interface
Advice.FieldValue

Indicates that the annotated parameter should be mapped to a field in the scope of the instrumented type.

public static @interface
Advice.Local

Declares the annotated parameter as a local variable that is created by Byte Buddy for the instrumented method.

protected static interface
Advice.MethodSizeHandler

A handler for computing the instrumented method's size.

private static class
Advice.NoExceptionHandler

A marker class that indicates that an advice method does not suppress any Throwable.

public static interface
Advice.OffsetMapping

Represents an offset mapping for an advice method to an alternative offset.

public static class
Advice.OnDefaultValue

A marker type to be used as an argument for OnMethodEnter#skipOn().

public static @interface
Advice.OnMethodEnter

Indicates that this method should be inlined before the matched method is invoked.

public static @interface
Advice.OnMethodExit

Indicates that this method should be executed before exiting the instrumented method.

public static class
Advice.OnNonDefaultValue

A marker type to be used as an argument for OnMethodEnter#skipOn().

public static @interface
Advice.Origin

Indicates that the annotated parameter should be mapped to a string representation of the instrumented method, a constant representing the Class declaring the adviced method or a Method, Constructor or java.lang.reflect.Executable representing this method.

public static interface
Advice.PostProcessor

A post processor for advice methods that is invoked after advice is executed.

public static @interface
Advice.Return

Indicates that the annotated parameter should be mapped to the return value of the instrumented method.

public static @interface
Advice.SelfCallHandle

Indicates that the annotated parameter should load a java.lang.invoke.MethodHandle that represents an invocation of the current method.

public static interface
Advice.StackMapFrameHandler

A handler for computing and translating stack map frames.

public static @interface
Advice.StubValue

Indicates that the annotated parameter should always return a boxed version of the instrumented method's return value (i.e. 0 for numeric values, false for boolean types and null for reference types).

public static @interface
Advice.This

Indicates that the annotated parameter should be mapped to the this reference of the instrumented method.

public static @interface
Advice.Thrown

Indicates that the annotated parameter should be mapped to the Throwable thrown by the instrumented method or to null if the method returned regularly.

public static @interface
Advice.Unused

Indicates that the annotated parameter should always return a default value (i.e. 0 for numeric values, false for boolean types and null for reference types).

public static class
Advice.WithCustomMapping

A builder step for creating an Advice that uses custom mappings of annotations to constant pool values.

Field Summary

Modifier and TypeField and Description
private final Assigner
assigner

The assigner to use.

private static final MethodDescription.InDefinedShape
private final Implementation
delegate

The delegate implementation to apply if this advice is used as an instrumentation.

private final Advice.ExceptionHandler
exceptionHandler

The exception handler to apply.

private static final MethodDescription.InDefinedShape
INLINE_ENTER

A reference to the OnMethodEnter#inline() method.

private static final MethodDescription.InDefinedShape
INLINE_EXIT

A reference to the OnMethodExit#inline() method.

private final Advice.Dispatcher.Resolved.ForMethodEnter
methodEnter

The dispatcher for instrumenting the instrumented method upon entering.

private final Advice.Dispatcher.Resolved.ForMethodExit
methodExit

The dispatcher for instrumenting the instrumented method upon exiting.

private static final MethodDescription.InDefinedShape
ON_THROWABLE

A reference to the OnMethodExit#onThrowable() method.

private static final MethodDescription.InDefinedShape
private static final MethodDescription.InDefinedShape
REPEAT_ON

A reference to the OnMethodExit#repeatOn() method.

private static final MethodDescription.InDefinedShape
private static final MethodDescription.InDefinedShape
SKIP_ON

A reference to the OnMethodEnter#skipOn() method.

private static final MethodDescription.InDefinedShape
SKIP_ON_INDEX

A reference to the OnMethodEnter#skipOnIndex() method.

private static final MethodDescription.InDefinedShape
SUPPRESS_ENTER

A reference to the OnMethodEnter#suppress() method.

private static final MethodDescription.InDefinedShape
SUPPRESS_EXIT

A reference to the OnMethodExit#suppress() method.

private static final ClassReader
UNDEFINED

Indicates that no class reader is available to an advice method.

Constructor Summary

AccessConstructor and Description
protected
Advice(Advice.Dispatcher.Resolved.ForMethodEnter
The dispatcher for instrumenting the instrumented method upon entering.
methodEnter
,
Advice.Dispatcher.Resolved.ForMethodExit
The dispatcher for instrumenting the instrumented method upon exiting.
methodExit
)

Creates a new advice.

private
Advice(Advice.Dispatcher.Resolved.ForMethodEnter
The dispatcher for instrumenting the instrumented method upon entering.
methodEnter
,
Advice.Dispatcher.Resolved.ForMethodExit
The dispatcher for instrumenting the instrumented method upon exiting.
methodExit
,
Assigner
The assigner to use.
assigner
,
Advice.ExceptionHandler
The exception handler to apply.
exceptionHandler
,
Implementation
The delegate implementation to apply if this advice is used as an instrumentation.
delegate
)

Creates a new advice.

Method Summary

Modifier and TypeMethod and Description
public ByteCodeAppender
appender(Implementation.Target
The target of the current implementation.
implementationTarget
)

Implements net.bytebuddy.implementation.Implementation.appender.

Creates a byte code appender that determines the implementation of the instrumented type's methods.
protected MethodVisitor

Returns:

A method visitor that applies this advice.
doWrap
(TypeDescription
The instrumented type.
instrumentedType
,
MethodDescription
The instrumented method.
instrumentedMethod
,
MethodVisitor
The method visitor to write to.
methodVisitor
,
Implementation.Context
The implementation context to use.
implementationContext
,
int
The ASM writer flags to use.
writerFlags
,
int
The ASM reader flags to use.
readerFlags
)

Wraps the method visitor to implement this advice.

private static Advice.Dispatcher.Unresolved

Returns:

A resolved dispatcher or the previous dispatcher if none was found.
locate
(Class<? extends Annotation>
The annotation type that indicates a given form of advice that is currently resolved.
type
,
MethodDescription.InDefinedShape
An annotation property that indicates if the advice method should be inlined.
property
,
Advice.Dispatcher.Unresolved
Any previous dispatcher that was discovered or the previous dispatcher if found.
dispatcher
,
MethodDescription.InDefinedShape
The method description that is considered as an advice method.
methodDescription
,
Advice.Delegator.Factory
The delegator factory to use.
delegatorFactory
)

Locates a dispatcher for the method if available.

public AsmVisitorWrapper.ForDeclaredMethods

Returns:

A suitable ASM visitor wrapper with the compute frames option enabled.
on
(ElementMatcher<? super MethodDescription>
The matcher identifying methods to apply the advice to.
matcher
)

Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods.

public InstrumentedType
prepare(InstrumentedType
The instrumented type in its current form.
instrumentedType
)

Implements net.bytebuddy.dynamic.scaffold.InstrumentedType.Prepareable.prepare.

Prepares a given instrumented type.
public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(Class<?>
The type declaring the advice.
advice
)

Implements advice where every matched method is advised by the given type's advisory methods.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(Class<?>
The type declaring the advice.
advice
,
ClassFileLocator
The class file locator for locating the advisory class's class file.
classFileLocator
)

Implements advice where every matched method is advised by the given type's advisory methods.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(TypeDescription
The type declaring the advice.
advice
)

Implements advice where every matched method is advised by the given type's advisory methods.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(TypeDescription
A description of the type declaring the advice.
advice
,
ClassFileLocator
The class file locator for locating the advisory class's class file.
classFileLocator
)

Implements advice where every matched method is advised by the given type's advisory methods.

protected static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(TypeDescription
A description of the type declaring the advice.
advice
,
Advice.PostProcessor.Factory
The post processor factory to use.
postProcessorFactory
,
ClassFileLocator
The class file locator for locating the advisory class's class file.
classFileLocator
,
List<? extends Advice.OffsetMapping.Factory<?>>
A list of custom factories for user generated offset mappings.
userFactories
,
Advice.Delegator.Factory
The delegator factory to use.
delegatorFactory
)

Creates a new advice.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(Class<?>
The type declaring the enter advice.
enterAdvice
,
Class<?>
The type declaring the exit advice.
exitAdvice
)

Implements advice where every matched method is advised by the given type's advisory methods.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(Class<?>
The type declaring the enter advice.
enterAdvice
,
Class<?>
The type declaring the exit advice.
exitAdvice
,
ClassFileLocator
The class file locator for locating the advisory class's class file.
classFileLocator
)

Implements advice where every matched method is advised by the given type's advisory methods.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(TypeDescription
The type declaring the enter advice.
enterAdvice
,
TypeDescription
The type declaring the exit advice.
exitAdvice
)

Implements advice where every matched method is advised by the given type's advisory methods.

public static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(TypeDescription
The type declaring the enter advice.
enterAdvice
,
TypeDescription
The type declaring the exit advice.
exitAdvice
,
ClassFileLocator
The class file locator for locating the advisory class's class file.
classFileLocator
)

Implements advice where every matched method is advised by the given type's advisory methods.

protected static Advice

Returns:

A method visitor wrapper representing the supplied advice.
to
(TypeDescription
The type declaring the enter advice.
enterAdvice
,
TypeDescription
The type declaring the exit advice.
exitAdvice
,
Advice.PostProcessor.Factory
The post processor factory to use.
postProcessorFactory
,
ClassFileLocator
The class file locator for locating the advisory class's class file.
classFileLocator
,
List<? extends Advice.OffsetMapping.Factory<?>>
A list of custom factories for user generated offset mappings.
userFactories
,
Advice.Delegator.Factory
The delegator factory to use.
delegatorFactory
)

Creates a new advice.

public Advice

Returns:

A version of this advice that uses the specified assigner.
withAssigner
(Assigner
The assigner to use,
assigner
)

Configures this advice to use the specified assigner.

public static Advice.WithCustomMapping

Returns:

A builder for an Advice instrumentation with custom values.
withCustomMapping
()

Allows for the configuration of custom annotations that are then bound to a dynamically computed, constant value.

public Advice

Returns:

A version of this advice that applies the supplied exception handler.
withExceptionHandler
(StackManipulation
The exception handler to apply.
exceptionHandler
)

Configures this advice to execute the given stack manipulation upon a suppressed exception.

public Advice

Returns:

A version of this advice that applies the supplied exception handler.
withExceptionHandler
(Advice.ExceptionHandler
The exception handler to apply.
exceptionHandler
)

Configures this advice to execute the given exception handler upon a suppressed exception.

public Advice

Returns:

A version of this advice that prints any suppressed exception.
withExceptionPrinting
()

Configures this advice to call Throwable#printStackTrace() upon a suppressed exception.

public MethodVisitor
wrap(TypeDescription
The instrumented type.
instrumentedType
,
MethodDescription
The method that is currently being defined.
instrumentedMethod
,
MethodVisitor
The original field visitor that defines the given method.
methodVisitor
,
Implementation.Context
The implementation context to use.
implementationContext
,
TypePool
The type pool to use.
typePool
,
int
The ASM net.bytebuddy.jar.asm.ClassWriter reader flags to consider.
writerFlags
,
int
The ASM net.bytebuddy.jar.asm.ClassReader reader flags to consider.
readerFlags
)

Implements net.bytebuddy.asm.AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper.wrap.

Wraps a method visitor.
public Implementation

Returns:

An implementation that applies the supplied implementation and wraps it with this advice.
wrap
(Implementation
The implementation to wrap.
implementation
)

Wraps the supplied implementation to have this advice applied around it.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait