net.bytebuddy.dynamic.scaffold.MethodGraph Java Examples

The following examples show how to use net.bytebuddy.dynamic.scaffold.MethodGraph. 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: RebaseImplementationTargetTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(methodGraph.locate(Mockito.any(MethodDescription.SignatureToken.class))).thenReturn(MethodGraph.Node.Unresolved.INSTANCE);
    when(instrumentedType.getSuperClass()).thenReturn(superClass);
    when(superClass.asErasure()).thenReturn(rawSuperClass);
    when(rawSuperClass.getInternalName()).thenReturn(BAR);
    when(rebasedMethod.getInternalName()).thenReturn(QUX);
    when(rebasedMethod.asToken(ElementMatchers.is(instrumentedType))).thenReturn(rebasedToken);
    when(rebasedMethod.getDescriptor()).thenReturn(FOO);
    when(rebasedMethod.asDefined()).thenReturn(rebasedMethod);
    when(rebasedMethod.getReturnType()).thenReturn(genericReturnType);
    when(rebasedMethod.getParameters()).thenReturn(new ParameterList.Empty<ParameterDescription.InDefinedShape>());
    when(rebasedMethod.getDeclaringType()).thenReturn(instrumentedType);
    when(rebasedMethod.asSignatureToken()).thenReturn(rebasedSignatureToken);
    super.setUp();
}
 
Example #2
Source File: TypeProxyCreationTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    for (ModifierContributor modifierContributor : AuxiliaryType.DEFAULT_TYPE_MODIFIER) {
        modifiers = modifiers | modifierContributor.getMask();
    }
    foo = TypeDescription.ForLoadedType.of(Foo.class);
    fooMethods = MethodGraph.Compiler.DEFAULT.compile(foo)
            .listNodes()
            .asMethodList()
            .filter(isVirtual().and(not(isFinal())).and(not(isDefaultFinalizer())));
    when(proxyMethod.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(proxyMethod, foo, foo, foo));
    when(proxyMethod.getDeclaringType()).thenReturn(foo);
    when(proxyMethod.getInternalName()).thenReturn(FOO);
    when(proxyMethod.getDescriptor()).thenReturn(FOO);
    when(proxyMethod.getReturnType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(proxyMethod.asDefined()).thenReturn(proxyMethod);
}
 
Example #3
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new substituting method visitor.
 *
 * @param methodVisitor         The method visitor to delegate to.
 * @param instrumentedType      The instrumented type.
 * @param instrumentedMethod    The instrumented method.
 * @param methodGraphCompiler   The method graph compiler to use.
 * @param strict                {@code true} if the method processing should be strict where an exception is raised if a member cannot be found.
 * @param replacement           The replacement to use for creating substitutions.
 * @param implementationContext The implementation context to use.
 * @param typePool              The type pool to use.
 * @param virtualPrivateCalls   {@code true}, virtual method calls might target private methods in accordance to the nest mate specification.
 */
protected SubstitutingMethodVisitor(MethodVisitor methodVisitor,
                                    TypeDescription instrumentedType,
                                    MethodDescription instrumentedMethod,
                                    MethodGraph.Compiler methodGraphCompiler,
                                    boolean strict,
                                    Replacement replacement,
                                    Implementation.Context implementationContext,
                                    TypePool typePool,
                                    boolean virtualPrivateCalls) {
    super(methodVisitor, instrumentedMethod);
    this.instrumentedType = instrumentedType;
    this.instrumentedMethod = instrumentedMethod;
    this.methodGraphCompiler = methodGraphCompiler;
    this.strict = strict;
    this.replacement = replacement;
    this.implementationContext = implementationContext;
    this.typePool = typePool;
    this.virtualPrivateCalls = virtualPrivateCalls;
    stackSizeBuffer = 0;
    localVariableExtension = 0;
}
 
Example #4
Source File: KanelaAgentBuilder.java    From kanela with Apache License 2.0 6 votes vote down vote up
private AgentBuilder newAgentBuilder() {
        val byteBuddy = new ByteBuddy()
            .with(TypeValidation.of(config.isDebugMode()))
            .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE);

        AgentBuilder agentBuilder = new AgentBuilder.Default(byteBuddy)
                .with(poolStrategyCache);


        agentBuilder = withRetransformationForRuntime(agentBuilder);
        agentBuilder = withBootstrapAttaching(agentBuilder);
        agentBuilder = withIgnore(agentBuilder);

        return agentBuilder
                .with(DefaultInstrumentationListener.instance())
                .with(additionalListeners());
}
 
Example #5
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the precomputed method graph.
 */
@SuppressFBWarnings(value = "SE_BAD_FIELD_STORE", justification = "Precomputed method graph is not intended for serialization")
PrecomputedMethodGraph() {
    LinkedHashMap<MethodDescription.SignatureToken, MethodGraph.Node> nodes = new LinkedHashMap<MethodDescription.SignatureToken, MethodGraph.Node>();
    MethodDescription callMethod = new MethodDescription.Latent(TypeDescription.ForLoadedType.of(Callable.class),
            "call",
            Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT,
            Collections.<TypeVariableToken>emptyList(),
            TypeDescription.Generic.OBJECT,
            Collections.<ParameterDescription.Token>emptyList(),
            Collections.singletonList(TypeDescription.Generic.OfNonGenericType.ForLoadedType.of(Exception.class)),
            Collections.<AnnotationDescription>emptyList(),
            AnnotationValue.UNDEFINED,
            TypeDescription.Generic.UNDEFINED);
    nodes.put(callMethod.asSignatureToken(), new MethodGraph.Node.Simple(callMethod));
    MethodDescription runMethod = new MethodDescription.Latent(TypeDescription.ForLoadedType.of(Runnable.class),
            "run",
            Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT,
            Collections.<TypeVariableToken>emptyList(),
            TypeDescription.Generic.VOID,
            Collections.<ParameterDescription.Token>emptyList(),
            Collections.<TypeDescription.Generic>emptyList(),
            Collections.<AnnotationDescription>emptyList(),
            AnnotationValue.UNDEFINED,
            TypeDescription.Generic.UNDEFINED);
    nodes.put(runMethod.asSignatureToken(), new MethodGraph.Node.Simple(runMethod));
    MethodGraph methodGraph = new MethodGraph.Simple(nodes);
    this.methodGraph = new MethodGraph.Linked.Delegation(methodGraph, methodGraph, Collections.<TypeDescription, MethodGraph>emptyMap());
}
 
Example #6
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new member substitution for a matched field that requires a specification for how to perform a substitution.
 *
 * @param methodGraphCompiler The method graph compiler to use.
 * @param typePoolResolver    The type pool resolver to use.
 * @param strict              {@code true} if the method processing should be strict where an exception is raised if a member cannot be found.
 * @param replacementFactory  The replacement factory to use.
 * @param matcher             A matcher for any field that should be substituted.
 * @param matchRead           {@code true} if read access to a field should be substituted.
 * @param matchWrite          {@code true} if write access to a field should be substituted.
 */
protected ForMatchedField(MethodGraph.Compiler methodGraphCompiler,
                          TypePoolResolver typePoolResolver,
                          boolean strict,
                          Replacement.Factory replacementFactory,
                          ElementMatcher<? super FieldDescription.InDefinedShape> matcher,
                          boolean matchRead,
                          boolean matchWrite) {
    super(methodGraphCompiler, typePoolResolver, strict, replacementFactory);
    this.matcher = matcher;
    this.matchRead = matchRead;
    this.matchWrite = matchWrite;
}
 
Example #7
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new member substitution for a matched method that requires a specification for how to perform a substitution.
 *
 * @param methodGraphCompiler The method graph compiler to use.
 * @param typePoolResolver    The type pool resolver to use.
 * @param strict              {@code true} if the method processing should be strict where an exception is raised if a member cannot be found.
 * @param replacementFactory  The replacement factory to use.
 * @param matcher             A matcher for any method or constructor that should be substituted.
 * @param includeVirtualCalls {@code true} if this specification includes virtual invocations.
 * @param includeSuperCalls   {@code true} if this specification includes {@code super} invocations.
 */
protected ForMatchedMethod(MethodGraph.Compiler methodGraphCompiler,
                           TypePoolResolver typePoolResolver,
                           boolean strict,
                           Replacement.Factory replacementFactory,
                           ElementMatcher<? super MethodDescription> matcher,
                           boolean includeVirtualCalls,
                           boolean includeSuperCalls) {
    super(methodGraphCompiler, typePoolResolver, strict, replacementFactory);
    this.matcher = matcher;
    this.includeVirtualCalls = includeVirtualCalls;
    this.includeSuperCalls = includeSuperCalls;
}
 
Example #8
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new member substitution.
 *
 * @param methodGraphCompiler The method graph compiler to use.
 * @param typePoolResolver    The type pool resolver to use.
 * @param strict              {@code true} if the method processing should be strict where an exception is raised if a member cannot be found.
 * @param replacementFactory  The replacement factory to use.
 */
protected MemberSubstitution(MethodGraph.Compiler methodGraphCompiler,
                             TypePoolResolver typePoolResolver,
                             boolean strict,
                             Replacement.Factory replacementFactory) {
    this.methodGraphCompiler = methodGraphCompiler;
    this.typePoolResolver = typePoolResolver;
    this.strict = strict;
    this.replacementFactory = replacementFactory;
}
 
Example #9
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new implementation delegate for a field delegation.
 *
 * @param fieldName           The name of the field that is target of the delegation.
 * @param methodGraphCompiler The method graph compiler to use.
 * @param parameterBinders    The parameter binders to use.
 * @param matcher             The matcher to use for filtering methods.
 */
protected ForField(String fieldName,
                   MethodGraph.Compiler methodGraphCompiler,
                   List<? extends TargetMethodAnnotationDrivenBinder.ParameterBinder<?>> parameterBinders,
                   ElementMatcher<? super MethodDescription> matcher) {
    this.fieldName = fieldName;
    this.methodGraphCompiler = methodGraphCompiler;
    this.parameterBinders = parameterBinders;
    this.matcher = matcher;
}
 
Example #10
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new implementation delegate for invoking methods on a supplied instance.
 *
 * @param fieldName           The name of the field that is target of the delegation.
 * @param methodGraphCompiler The method graph compiler to use.
 * @param parameterBinders    The parameter binders to use.
 * @param matcher             The matcher to use for filtering methods.
 * @param target              The target instance.
 * @param fieldType           The field's type.
 */
protected WithInstance(String fieldName,
                       MethodGraph.Compiler methodGraphCompiler,
                       List<? extends TargetMethodAnnotationDrivenBinder.ParameterBinder<?>> parameterBinders,
                       ElementMatcher<? super MethodDescription> matcher,
                       Object target,
                       TypeDescription.Generic fieldType) {
    super(fieldName, methodGraphCompiler, parameterBinders, matcher);
    this.target = target;
    this.fieldType = fieldType;
}
 
Example #11
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new implementation delegate for a method return value delegation.
 *
 * @param name                The name of the method to invoke.
 * @param methodGraphCompiler The method graph compiler to use.
 * @param parameterBinders    The parameter binders to use.
 * @param matcher             The matcher to use for filtering methods.
 */
protected ForMethodReturn(String name,
                          MethodGraph.Compiler methodGraphCompiler,
                          List<? extends TargetMethodAnnotationDrivenBinder.ParameterBinder<?>> parameterBinders,
                          ElementMatcher<? super MethodDescription> matcher) {
    this.name = name;
    this.methodGraphCompiler = methodGraphCompiler;
    this.parameterBinders = parameterBinders;
    this.matcher = matcher;
}
 
Example #12
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Creates a lambda expression using the JVM's lambda meta factory. The method that is implementing the lambda expression is provided
 * the explicit arguments first and the functional interface's method second.
 * </p>
 * <p>
 * <b>Important</b>: Byte Buddy does not validate that the provided arguments are correct considering the required arguments of the bound
 * functional interface. Binding an incorrect number of arguments or arguments of incompatible types does not create illegal byte code
 * but yields a runtime error when the call site is first used. This is done to support future extensions or alternative implementations
 * of the Java virtual machine.
 * </p>
 *
 * @param methodDescription   The method that implements the lambda expression.
 * @param functionalInterface The functional interface that is an instance of the lambda expression.
 * @param methodGraphCompiler The method graph compiler to use.
 * @return A builder for creating a lambda expression.
 */
public static WithImplicitArguments lambda(MethodDescription.InDefinedShape methodDescription,
                                           TypeDescription functionalInterface,
                                           MethodGraph.Compiler methodGraphCompiler) {
    if (!functionalInterface.isInterface()) {
        throw new IllegalArgumentException(functionalInterface + " is not an interface type");
    }
    MethodList<?> methods = methodGraphCompiler.compile(functionalInterface)
            .listNodes()
            .asMethodList()
            .filter(isAbstract());
    if (methods.size() != 1) {
        throw new IllegalArgumentException(functionalInterface + " does not define exactly one abstract method: " + methods);
    }
    return bootstrap(new MethodDescription.Latent(new TypeDescription.Latent("java.lang.invoke.LambdaMetafactory",
                    Opcodes.ACC_PUBLIC,
                    TypeDescription.Generic.OBJECT),
                    "metafactory",
                    Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC,
                    Collections.<TypeVariableToken>emptyList(),
                    JavaType.CALL_SITE.getTypeStub().asGenericType(),
                    Arrays.asList(new ParameterDescription.Token(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(TypeDescription.STRING.asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_TYPE.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_TYPE.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_HANDLE.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_TYPE.getTypeStub().asGenericType())),
                    Collections.<TypeDescription.Generic>emptyList(),
                    Collections.<AnnotationDescription>emptyList(),
                    AnnotationValue.UNDEFINED,
                    TypeDescription.Generic.UNDEFINED),
            JavaConstant.MethodType.of(methods.asDefined().getOnly()),
            JavaConstant.MethodHandle.of(methodDescription),
            JavaConstant.MethodType.of(methods.asDefined().getOnly())).invoke(methods.asDefined().getOnly().getInternalName());
}
 
Example #13
Source File: SubclassImplementationTarget.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a special method invocation for a non-constructor invocation.
 *
 * @param token A token describing the method to be invoked.
 * @return A special method invocation for a method representing the given method token, if available.
 */
private Implementation.SpecialMethodInvocation invokeMethod(MethodDescription.SignatureToken token) {
    MethodGraph.Node methodNode = methodGraph.getSuperClassGraph().locate(token);
    return methodNode.getSort().isUnique()
            ? Implementation.SpecialMethodInvocation.Simple.of(methodNode.getRepresentative(), instrumentedType.getSuperClass().asErasure())
            : Implementation.SpecialMethodInvocation.Illegal.INSTANCE;
}
 
Example #14
Source File: DecoratingDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new decorating dynamic type builder.
 *
 * @param instrumentedType             The instrumented type to decorate.
 * @param typeAttributeAppender        The type attribute appender to apply onto the instrumented type.
 * @param asmVisitorWrapper            The ASM visitor wrapper to apply onto the class writer.
 * @param classFileVersion             The class file version to define auxiliary types in.
 * @param auxiliaryTypeNamingStrategy  The naming strategy for auxiliary types to apply.
 * @param annotationValueFilterFactory The annotation value filter factory to apply.
 * @param annotationRetention          The annotation retention to apply.
 * @param implementationContextFactory The implementation context factory to apply.
 * @param methodGraphCompiler          The method graph compiler to use.
 * @param typeValidation               Determines if a type should be explicitly validated.
 * @param classWriterStrategy          The class writer strategy to use.
 * @param ignoredMethods               A matcher for identifying methods that should be excluded from instrumentation.
 * @param auxiliaryTypes               A list of explicitly required auxiliary types.
 * @param classFileLocator             The class file locator for locating the original type's class file.
 */
protected DecoratingDynamicTypeBuilder(TypeDescription instrumentedType,
                                       TypeAttributeAppender typeAttributeAppender,
                                       AsmVisitorWrapper asmVisitorWrapper,
                                       ClassFileVersion classFileVersion,
                                       AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy,
                                       AnnotationValueFilter.Factory annotationValueFilterFactory,
                                       AnnotationRetention annotationRetention,
                                       Implementation.Context.Factory implementationContextFactory,
                                       MethodGraph.Compiler methodGraphCompiler,
                                       TypeValidation typeValidation,
                                       ClassWriterStrategy classWriterStrategy,
                                       LatentMatcher<? super MethodDescription> ignoredMethods,
                                       List<DynamicType> auxiliaryTypes,
                                       ClassFileLocator classFileLocator) {
    this.instrumentedType = instrumentedType;
    this.typeAttributeAppender = typeAttributeAppender;
    this.asmVisitorWrapper = asmVisitorWrapper;
    this.classFileVersion = classFileVersion;
    this.auxiliaryTypeNamingStrategy = auxiliaryTypeNamingStrategy;
    this.annotationValueFilterFactory = annotationValueFilterFactory;
    this.annotationRetention = annotationRetention;
    this.implementationContextFactory = implementationContextFactory;
    this.methodGraphCompiler = methodGraphCompiler;
    this.typeValidation = typeValidation;
    this.classWriterStrategy = classWriterStrategy;
    this.ignoredMethods = ignoredMethods;
    this.auxiliaryTypes = auxiliaryTypes;
    this.classFileLocator = classFileLocator;
}
 
Example #15
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new member substitution that requires a specification for how to perform a substitution.
 *
 * @param methodGraphCompiler The method graph compiler to use.
 * @param typePoolResolver    The type pool resolver to use.
 * @param strict              {@code true} if the method processing should be strict where an exception is raised if a member cannot be found.
 * @param replacementFactory  The replacement factory to use for creating substitutions.
 */
protected WithoutSpecification(MethodGraph.Compiler methodGraphCompiler,
                               TypePoolResolver typePoolResolver,
                               boolean strict,
                               Replacement.Factory replacementFactory) {
    this.methodGraphCompiler = methodGraphCompiler;
    this.typePoolResolver = typePoolResolver;
    this.strict = strict;
    this.replacementFactory = replacementFactory;
}
 
Example #16
Source File: EnhancerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static MethodDescription getterOf(FieldDescription persistentField) {
	MethodList<?> methodList = MethodGraph.Compiler.DEFAULT.compile( persistentField.getDeclaringType().asErasure() )
			.listNodes()
			.asMethodList()
			.filter( isGetter(persistentField.getName() ) );
	if ( methodList.size() == 1 ) {
		return methodList.getOnly();
	}
	else {
		return null;
	}
}
 
Example #17
Source File: SubclassImplementationTargetTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    when(superGraph.locate(Mockito.any(MethodDescription.SignatureToken.class))).thenReturn(MethodGraph.Node.Unresolved.INSTANCE);
    when(superGraph.locate(invokableToken)).thenReturn(new MethodGraph.Node.Simple(invokableMethod));
    when(instrumentedType.getSuperClass()).thenReturn(superClass);
    when(superClass.asErasure()).thenReturn(rawSuperClass);
    when(superClass.asGenericType()).thenReturn(superClass);
    when(rawSuperClass.asGenericType()).thenReturn(superClass);
    when(rawSuperClass.asErasure()).thenReturn(rawSuperClass);
    when(rawSuperClass.getInternalName()).thenReturn(BAR);
    when(superClass.getDeclaredMethods())
            .thenReturn(new MethodList.Explicit<MethodDescription.InGenericShape>(superClassConstructor));
    when(superClassConstructor.asDefined()).thenReturn(definedSuperClassConstructor);
    when(definedSuperClassConstructor.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(definedSuperClassConstructor.getDeclaringType()).thenReturn(rawSuperClass);
    when(definedSuperClassConstructor.isConstructor()).thenReturn(true);
    when(superClassConstructor.isVisibleTo(instrumentedType)).thenReturn(true);
    when(superClassConstructor.asSignatureToken()).thenReturn(superConstructorToken);
    when(definedSuperClassConstructor.getInternalName()).thenReturn(QUX);
    when(definedSuperClassConstructor.getDescriptor()).thenReturn(BAZ);
    when(superClassConstructor.isConstructor()).thenReturn(true);
    when(superClassConstructor.getDeclaringType()).thenReturn(superClass);
    when(superClassConstructor.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(superClassConstructor.getParameters()).thenReturn(new ParameterList.Empty<ParameterDescription.InGenericShape>());
    when(invokableToken.getName()).thenReturn(FOO);
    when(superConstructorToken.getName()).thenReturn(MethodDescription.CONSTRUCTOR_INTERNAL_NAME);
    super.setUp();
}
 
Example #18
Source File: AbstractImplementationTargetTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(instrumentedType.asErasure()).thenReturn(instrumentedType);
    when(instrumentedType.getInternalName()).thenReturn(BAZ);
    when(methodGraph.getSuperClassGraph()).thenReturn(superGraph);
    when(superGraph.locate(any(MethodDescription.SignatureToken.class))).thenReturn(MethodGraph.Node.Unresolved.INSTANCE);
    when(superGraph.locate(invokableToken)).thenReturn(new MethodGraph.Node.Simple(invokableMethod));
    when(methodGraph.getInterfaceGraph(defaultMethodDeclaringType)).thenReturn(defaultGraph);
    when(defaultGraph.locate(any(MethodDescription.SignatureToken.class))).thenReturn(MethodGraph.Node.Unresolved.INSTANCE);
    when(defaultGraph.locate(defaultToken)).thenReturn(new MethodGraph.Node.Simple(defaultMethod));
    when(methodDeclaringType.asErasure()).thenReturn(methodDeclaringType);
    when(invokableMethod.getDeclaringType()).thenReturn(methodDeclaringType);
    when(invokableMethod.getReturnType()).thenReturn(genericReturnType);
    when(returnType.getStackSize()).thenReturn(StackSize.ZERO);
    when(genericReturnType.getStackSize()).thenReturn(StackSize.ZERO);
    when(returnType.asErasure()).thenReturn(returnType);
    when(invokableMethod.getInternalName()).thenReturn(FOO);
    when(invokableMethod.getDescriptor()).thenReturn(QUX);
    when(invokableMethod.asSignatureToken()).thenReturn(invokableToken);
    when(invokableMethod.asDefined()).thenReturn(invokableMethod);
    when(defaultMethod.getInternalName()).thenReturn(QUXBAZ);
    when(defaultMethod.getDescriptor()).thenReturn(FOOBAZ);
    when(defaultMethod.getDeclaringType()).thenReturn(defaultMethodDeclaringType);
    when(defaultMethod.getReturnType()).thenReturn(genericReturnType);
    when(defaultMethod.asSignatureToken()).thenReturn(defaultToken);
    when(defaultMethod.asDefined()).thenReturn(defaultMethod);
    when(defaultMethod.isSpecializableFor(defaultMethodDeclaringType)).thenReturn(true);
    when(defaultMethodDeclaringType.isInterface()).thenReturn(true);
    when(defaultMethodDeclaringType.asErasure()).thenReturn(defaultMethodDeclaringType);
    when(defaultMethodDeclaringType.getInternalName()).thenReturn(BAZBAR);
    when(genericReturnType.asErasure()).thenReturn(returnType);
    when(genericReturnType.asGenericType()).thenReturn(genericReturnType);
    when(returnType.asGenericType()).thenReturn(genericReturnType);
    when(genericInstrumentedType.asErasure()).thenReturn(instrumentedType);
    when(genericInstrumentedType.asGenericType()).thenReturn(genericInstrumentedType);
    when(instrumentedType.asGenericType()).thenReturn(genericInstrumentedType);
    defaultMethodInvocation = Implementation.Target.AbstractBase.DefaultMethodInvocation.ENABLED;
}
 
Example #19
Source File: TypePoolDefaultWithLazyResolutionTypeDescriptionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericResolutionIsLazyForSimpleCreation() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .with(MethodGraph.Empty.INSTANCE)
            .with(InstrumentedType.Factory.Default.FROZEN)
            .redefine(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()), classFileLocator)
            .make();
    verify(classFileLocator, times(2)).locate(GenericType.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #20
Source File: TypePoolDefaultWithLazyResolutionTypeDescriptionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonGenericResolutionIsLazyForSimpleCreation() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .with(MethodGraph.Empty.INSTANCE)
            .with(InstrumentedType.Factory.Default.FROZEN)
            .redefine(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()), classFileLocator)
            .make();
    verify(classFileLocator, times(2)).locate(NonGenericType.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #21
Source File: TypePoolDefaultWithLazyResolutionTypeDescriptionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonGenericResolutionIsLazyForSimpleCreationNonFrozen() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .with(MethodGraph.Empty.INSTANCE)
            .with(InstrumentedType.Factory.Default.MODIFIABLE)
            .redefine(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()), classFileLocator)
            .make();
    verify(classFileLocator, times(2)).locate(NonGenericType.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #22
Source File: DecoratingDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new decorating dynamic type builder.
 *
 * @param instrumentedType             The instrumented type to decorate.
 * @param classFileVersion             The class file version to define auxiliary types in.
 * @param auxiliaryTypeNamingStrategy  The naming strategy for auxiliary types to apply.
 * @param annotationValueFilterFactory The annotation value filter factory to apply.
 * @param annotationRetention          The annotation retention to apply.
 * @param implementationContextFactory The implementation context factory to apply.
 * @param methodGraphCompiler          The method graph compiler to use.
 * @param typeValidation               Determines if a type should be explicitly validated.
 * @param classWriterStrategy          The class writer strategy to use.
 * @param ignoredMethods               A matcher for identifying methods that should be excluded from instrumentation.
 * @param classFileLocator             The class file locator for locating the original type's class file.
 */
public DecoratingDynamicTypeBuilder(TypeDescription instrumentedType,
                                    ClassFileVersion classFileVersion,
                                    AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy,
                                    AnnotationValueFilter.Factory annotationValueFilterFactory,
                                    AnnotationRetention annotationRetention,
                                    Implementation.Context.Factory implementationContextFactory,
                                    MethodGraph.Compiler methodGraphCompiler,
                                    TypeValidation typeValidation,
                                    ClassWriterStrategy classWriterStrategy,
                                    LatentMatcher<? super MethodDescription> ignoredMethods,
                                    ClassFileLocator classFileLocator) {
    this(instrumentedType,
            annotationRetention.isEnabled()
                    ? new TypeAttributeAppender.ForInstrumentedType.Differentiating(instrumentedType)
                    : TypeAttributeAppender.ForInstrumentedType.INSTANCE,
            AsmVisitorWrapper.NoOp.INSTANCE,
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            classWriterStrategy,
            ignoredMethods,
            Collections.<DynamicType>emptyList(),
            classFileLocator);
}
 
Example #23
Source File: EntryPoint.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public ByteBuddy byteBuddy(ClassFileVersion classFileVersion) {
    return new ByteBuddy(classFileVersion)
            .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE)
            .with(Implementation.Context.Disabled.Factory.INSTANCE);
}
 
Example #24
Source File: RebaseImplementationTarget.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Implementation.Target make(TypeDescription instrumentedType, MethodGraph.Linked methodGraph, ClassFileVersion classFileVersion) {
    return RebaseImplementationTarget.of(instrumentedType, methodGraph, classFileVersion, methodRebaseResolver);
}
 
Example #25
Source File: Implementation.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
@Override
protected SpecialMethodInvocation apply(MethodGraph.Node node, TypeDescription targetType) {
    return node.getSort().isUnique()
            ? SpecialMethodInvocation.Simple.of(node.getRepresentative(), targetType)
            : SpecialMethodInvocation.Illegal.INSTANCE;
}
 
Example #26
Source File: SubclassImplementationTarget.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Implementation.Target make(TypeDescription instrumentedType, MethodGraph.Linked methodGraph, ClassFileVersion classFileVersion) {
    return new SubclassImplementationTarget(instrumentedType, methodGraph, DefaultMethodInvocation.of(classFileVersion), originTypeResolver);
}
 
Example #27
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodGraph.Linked compile(TypeDefinition typeDefinition, TypeDescription viewPoint) {
    return methodGraph;
}
 
Example #28
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodGraph.Linked compile(TypeDescription typeDescription) {
    return compile(typeDescription, typeDescription);
}
 
Example #29
Source File: RebaseImplementationTarget.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new rebase implementation target.
 *
 * @param instrumentedType     The instrumented type.
 * @param methodGraph          A method graph of the instrumented type.
 * @param classFileVersion     The type's class file version.
 * @param methodRebaseResolver A method rebase resolver to be used when calling a rebased method.
 * @return An implementation target for the given input.
 */
protected static Implementation.Target of(TypeDescription instrumentedType,
                                          MethodGraph.Linked methodGraph,
                                          ClassFileVersion classFileVersion,
                                          MethodRebaseResolver methodRebaseResolver) {
    return new RebaseImplementationTarget(instrumentedType, methodGraph, DefaultMethodInvocation.of(classFileVersion), methodRebaseResolver.asTokenMap());
}
 
Example #30
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates any intercepted method to invoke a non-{@code static} method that is declared by the supplied type's instance or any
 * of its super types. To be considered a valid delegation target, a method must be visible and accessible to the instrumented type.
 * This is the case if the method's declaring type is either public or in the same package as the instrumented type and if the method
 * is either public or non-private and in the same package as the instrumented type. Private methods can only be used as
 * a delegation target if the delegation is targeting the instrumented type.
 *
 * @param target              The target instance for the delegation.
 * @param typeDefinition      The most specific type of which {@code target} should be considered. Must be a super type of the target's actual type.
 * @param fieldName           The name of the field that is holding the {@code target} instance.
 * @param methodGraphCompiler The method graph compiler to use.
 * @return A method delegation that redirects method calls to a static method of the supplied type.
 */
public MethodDelegation to(Object target, TypeDefinition typeDefinition, String fieldName, MethodGraph.Compiler methodGraphCompiler) {
    if (!typeDefinition.asErasure().isInstance(target)) {
        throw new IllegalArgumentException(target + " is not an instance of " + typeDefinition);
    }
    return new MethodDelegation(new ImplementationDelegate.ForField.WithInstance(fieldName,
            methodGraphCompiler,
            parameterBinders,
            matcher,
            target,
            typeDefinition.asGenericType()), parameterBinders, ambiguityResolver, bindingResolver);
}