net.bytebuddy.description.method.MethodDescription Java Examples

The following examples show how to use net.bytebuddy.description.method.MethodDescription. 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: RabbitMQConsumerInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new DeclaredInstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return named(ENHANCE_METHOD_DISPATCH).and(takesArgumentWithType(2, "com.rabbitmq.client.AMQP$BasicProperties"));
            }

            @Override
            public String getMethodsInterceptor() {
                return INTERCEPTOR_CLASS;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #2
Source File: KafkaTemplateCallbackInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return takesArgumentWithType(0, CONSTRUCTOR_INTERCEPT_TYPE);
            }

            @Override
            public String getConstructorInterceptor() {
                return CONSTRUCTOR_INTERCEPTOR_CLASS;
            }
        }
    };
}
 
Example #3
Source File: AbstractControllerInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return any();
            }

            @Override
            public String getConstructorInterceptor() {
                return "org.apache.skywalking.apm.plugin.spring.mvc.v5.ControllerConstructorInterceptor";
            }
        }
    };
}
 
Example #4
Source File: AbstractTypeDescriptionGenericVariableDefiningTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@JavaVersionRule.Enforce(8)
public void testGenericInnerTypeAnnotationReceiverTypeOnConstructor() throws Exception {
    Class<? extends Annotation> typeAnnotation = (Class<? extends Annotation>) Class.forName(TYPE_ANNOTATION);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotation).getDeclaredMethods().getOnly();
    TypeDescription.Generic receiverType = describe(Class.forName(RECEIVER_TYPE_SAMPLE + "$" + GENERIC + "$" + INNER))
            .getDeclaredMethods()
            .filter(isConstructor())
            .getOnly()
            .getReceiverType();
    assertThat(receiverType, notNullValue(TypeDescription.Generic.class));
    assertThat(receiverType.getSort(), is(TypeDefinition.Sort.PARAMETERIZED));
    assertThat(receiverType.asErasure().represents(Class.forName(RECEIVER_TYPE_SAMPLE + "$" + GENERIC)), is(true));
    assertThat(receiverType.getDeclaredAnnotations().size(), is(1));
    assertThat(receiverType.getDeclaredAnnotations().isAnnotationPresent(typeAnnotation), is(true));
    assertThat(receiverType.getDeclaredAnnotations().ofType(typeAnnotation).getValue(value).resolve(Integer.class), is(10));
    assertThat(receiverType.getTypeArguments().getOnly().getSort(), is(TypeDefinition.Sort.VARIABLE));
    assertThat(receiverType.getTypeArguments().getOnly().getSymbol(), is(T));
    assertThat(receiverType.getTypeArguments().getOnly().getDeclaredAnnotations().size(), is(1));
    assertThat(receiverType.getTypeArguments().getOnly().getDeclaredAnnotations().isAnnotationPresent(typeAnnotation), is(true));
    assertThat(receiverType.getTypeArguments().getOnly().getDeclaredAnnotations().ofType(typeAnnotation).getValue(value).resolve(Integer.class), is(11));
    assertThat(receiverType.getOwnerType().getSort(), is(TypeDefinition.Sort.NON_GENERIC));
    assertThat(receiverType.getOwnerType().represents(Class.forName(RECEIVER_TYPE_SAMPLE)), is(true));
}
 
Example #5
Source File: PreparedStatementInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return named("execute").or(named("executeQuery"))
                                       .or(named("executeUpdate"))
                                       .or(named("executeLargeUpdate"));
            }

            @Override
            public String getMethodsInterceptor() {
                return SERVICE_METHOD_INTERCEPTOR;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #6
Source File: AbstractNutzHttpInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return named(DO_SEND_METHOD_NAME);
            }

            @Override
            public String getMethodsInterceptor() {
                return DO_SEND_INTERCEPTOR;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #7
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitTypeInitializer() throws Exception {
    assertThat(createPlain()
            .defineField(FOO, String.class, Ownership.STATIC, Visibility.PUBLIC)
            .initializer(new ByteCodeAppender() {
                public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
                    return new Size(new StackManipulation.Compound(
                            new TextConstant(FOO),
                            FieldAccess.forField(instrumentedMethod.getDeclaringType().getDeclaredFields().filter(named(FOO)).getOnly()).write()
                    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
                }
            }).make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredField(FOO)
            .get(null), is((Object) FOO));
}
 
Example #8
Source File: SkywalkingContinuationActivation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return any();
            }

            @Override
            public String getConstructorInterceptor() {
                return CONSTRUCTOR_INTERCEPTOR;
            }
        }
    };
}
 
Example #9
Source File: ExecuteInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return named("execute0");
            }

            @Override
            public String getMethodsInterceptor() {
                return EXECUTE_INTERCEPTOR_CLASS;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #10
Source File: CallableInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return named("execute").or(named("executeQuery")).or(named("executeUpdate"));
            }

            @Override
            public String getMethodsInterceptor() {
                return SERVICE_METHOD_INTERCEPTOR;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #11
Source File: RouteStateInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
            new ConstructorInterceptPoint() {
                @Override
                public ElementMatcher<MethodDescription> getConstructorMatcher() {
                    return takesArgument(8, List.class);
                }

                @Override
                public String getConstructorInterceptor() {
                    return INTERCEPT_CLASS;
                }
            }
    };
}
 
Example #12
Source File: MinimalHttpClientInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return named("doExecute");
            }

            @Override
            public String getMethodsInterceptor() {
                return getInstanceMethodsInterceptor();
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #13
Source File: AdviceTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssigningEnterPostProcessorInline() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(PostProcessorInlineTest.class)
            .visit(Advice.withCustomMapping().with(new Advice.PostProcessor.Factory() {
                @Override
                public Advice.PostProcessor make(final MethodDescription.InDefinedShape advice, boolean exit) {
                    return new Advice.PostProcessor() {
                        @Override
                        public StackManipulation resolve(TypeDescription instrumentedType,
                                                         MethodDescription instrumentedMethod,
                                                         Assigner assigner,
                                                         Advice.ArgumentHandler argumentHandler) {
                            return new StackManipulation.Compound(
                                MethodVariableAccess.of(advice.getReturnType()).loadFrom(argumentHandler.enter()),
                                MethodVariableAccess.store(instrumentedMethod.getParameters().get(0))
                            );
                        }
                    };
                }
            }).to(PostProcessorInlineTest.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO, String.class).invoke(type.getDeclaredConstructor().newInstance(), BAR), is((Object) FOO));
}
 
Example #14
Source File: TransportServiceInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return any();
            }

            @Override
            public String getConstructorInterceptor() {
                return ENHANCE_CLASS;
            }
        }
    };
}
 
Example #15
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testTypeVariableOnTypeAnnotationClassBound() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Class<?> type = createPlain()
            .typeVariable(FOO, TypeDescription.Generic.Builder.rawType(Object.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE * 2).build()))
            .annotateTypeVariable(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE).build())
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(type.getTypeParameters().length, is(1));
    assertThat(type.getTypeParameters()[0].getBounds().length, is(1));
    assertThat(type.getTypeParameters()[0].getBounds()[0], is((Object) Object.class));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[0]).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[0]).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[0]).ofTypeVariableBoundType(0)
            .asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(type.getTypeParameters()[0]).ofTypeVariableBoundType(0)
            .asList().ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(INTEGER_VALUE * 2));
}
 
Example #16
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericClassMultipleEvolution() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(GenericClassBase.Intermediate.Inner.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 1));
    MethodDescription.SignatureToken token = typeDescription.getDeclaredMethods().filter(isMethod().and(ElementMatchers.not(isBridge()))).getOnly().asSignatureToken();
    MethodGraph.Node node = methodGraph.locate(token);
    MethodDescription.SignatureToken firstBridgeToken = typeDescription.getSuperClass().getDeclaredMethods()
            .filter(isMethod().and(ElementMatchers.not(isBridge()))).getOnly().asDefined().asSignatureToken();
    MethodDescription.SignatureToken secondBridgeToken = typeDescription.getSuperClass().getSuperClass().getDeclaredMethods()
            .filter(isMethod()).getOnly().asDefined().asSignatureToken();
    assertThat(node, is(methodGraph.locate(firstBridgeToken)));
    assertThat(node, is(methodGraph.locate(secondBridgeToken)));
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getMethodTypes().size(), is(3));
    assertThat(node.getMethodTypes().contains(token.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(firstBridgeToken.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(secondBridgeToken.asTypeToken()), is(true));
    assertThat(node.getVisibility(), is(Visibility.PUBLIC));
}
 
Example #17
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodVisitor wrap(TypeDescription instrumentedType,
                          MethodDescription instrumentedMethod,
                          MethodVisitor methodVisitor,
                          Implementation.Context implementationContext,
                          TypePool typePool,
                          int writerFlags,
                          int readerFlags) {
    for (MethodVisitorWrapper methodVisitorWrapper : methodVisitorWrappers) {
        methodVisitor = methodVisitorWrapper.wrap(instrumentedType,
                instrumentedMethod,
                methodVisitor,
                implementationContext,
                typePool,
                writerFlags,
                readerFlags);
    }
    return methodVisitor;
}
 
Example #18
Source File: HttpClientRequestImplInstrumentation.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[]{
            new InstanceMethodsInterceptPoint() {
                @Override
                public ElementMatcher<MethodDescription> getMethodsMatcher() {
                    return named("end")
                            .or(named("sendHead").and(takesArguments(1)));
                }

                @Override
                public String getMethodsInterceptor() {
                    return INTERCEPT_CLASS;
                }

                @Override
                public boolean isOverrideArgs() {
                    return false;
                }
            }
    };
}
 
Example #19
Source File: AbstractTypeDescriptionGenericTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTypeVariableErasedBound() throws Exception {
    TypeDescription.Generic typeDescription = describeType(MemberVariable.class.getDeclaredField(BAR)).getSuperClass();
    assertThat(typeDescription.getSort(), is(TypeDefinition.Sort.NON_GENERIC));
    MethodDescription methodDescription = typeDescription.getDeclaredMethods().filter(named(FOO)).getOnly();
    assertThat(methodDescription.getReturnType().getSort(), is(TypeDefinition.Sort.NON_GENERIC));
    assertThat(methodDescription.getReturnType().asErasure(), is(TypeDescription.OBJECT));
}
 
Example #20
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new dynamic method invocation with implicit arguments and an implicit invocation target.
 *
 * @param bootstrap          The bootstrap method or constructor.
 * @param arguments          The arguments that are provided to the bootstrap method.
 * @param invocationProvider The target provided that identifies the method to be bootstrapped.
 * @param terminationHandler A handler that handles the method return.
 * @param assigner           The assigner to be used.
 * @param typing             Indicates if dynamic type castings should be attempted for incompatible assignments.
 */
protected WithImplicitTarget(MethodDescription.InDefinedShape bootstrap,
                             List<?> arguments,
                             InvocationProvider invocationProvider,
                             TerminationHandler terminationHandler,
                             Assigner assigner,
                             Assigner.Typing typing) {
    super(bootstrap,
            arguments,
            invocationProvider,
            terminationHandler,
            assigner,
            typing);
}
 
Example #21
Source File: MethodAttributeAppenderExplicitTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
@Override
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    super.setUp();
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Explicit<ParameterDescription>(parameterDescription));
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
}
 
Example #22
Source File: MethodGraph.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a method graph that contains all of the provided methods as simple nodes.
 *
 * @param methodDescriptions A list of method descriptions to be represented as simple nodes.
 * @return A method graph that represents all of the provided methods as simple nodes.
 */
public static MethodGraph of(List<? extends MethodDescription> methodDescriptions) {
    LinkedHashMap<MethodDescription.SignatureToken, Node> nodes = new LinkedHashMap<MethodDescription.SignatureToken, Node>();
    for (MethodDescription methodDescription : methodDescriptions) {
        nodes.put(methodDescription.asSignatureToken(), new Node.Simple(methodDescription));
    }
    return new Simple(nodes);
}
 
Example #23
Source File: MethodOverrideMatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoMatchMatcher() throws Exception {
    when(declaredTypeMethod.asSignatureToken()).thenReturn(token);
    when(superTypeMethod.asSignatureToken()).thenReturn(token);
    when(interfaceTypeMethod.asSignatureToken()).thenReturn(token);
    assertThat(new MethodOverrideMatcher<MethodDescription>(typeMatcher).matches(methodDescription), is(false));
    verify(typeMatcher).matches(declaringType);
    verify(typeMatcher).matches(superType);
    verify(typeMatcher).matches(interfaceType);
    verifyNoMoreInteractions(typeMatcher);
}
 
Example #24
Source File: BytecodeProviderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod) {
	methodVisitor.visitLdcInsn( getters.length );
	methodVisitor.visitTypeInsn( Opcodes.ANEWARRAY, Type.getInternalName( Object.class ) );
	int index = 0;
	for ( Method getter : getters ) {
		methodVisitor.visitInsn( Opcodes.DUP );
		methodVisitor.visitLdcInsn( index++ );
		methodVisitor.visitVarInsn( Opcodes.ALOAD, 1 );
		methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, Type.getInternalName( clazz ) );
		methodVisitor.visitMethodInsn(
				Opcodes.INVOKEVIRTUAL,
				Type.getInternalName( clazz ),
				getter.getName(),
				Type.getMethodDescriptor( getter ),
				false
		);
		if ( getter.getReturnType().isPrimitive() ) {
			PrimitiveBoxingDelegate.forPrimitive( new TypeDescription.ForLoadedType( getter.getReturnType() ) )
					.assignBoxedTo(
							TypeDescription.Generic.OBJECT,
							ReferenceTypeAwareAssigner.INSTANCE,
							Assigner.Typing.STATIC
					)
					.apply( methodVisitor, implementationContext );
		}
		methodVisitor.visitInsn( Opcodes.AASTORE );
	}
	methodVisitor.visitInsn( Opcodes.ARETURN );
	return new Size( 6, instrumentedMethod.getStackSize() );
}
 
Example #25
Source File: TypeProxyCreationTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testForDefaultMethodConstruction() throws Exception {
    when(implementationTarget.getInstrumentedType()).thenReturn(foo);
    when(invocationFactory.invoke(eq(implementationTarget), eq(foo), any(MethodDescription.class)))
            .thenReturn(specialMethodInvocation);
    when(specialMethodInvocation.isValid()).thenReturn(true);
    when(specialMethodInvocation.apply(any(MethodVisitor.class), any(Implementation.Context.class)))
            .thenReturn(new StackManipulation.Size(0, 0));
    when(methodAccessorFactory.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT)).thenReturn(proxyMethod);
    StackManipulation stackManipulation = new TypeProxy.ForDefaultMethod(foo,
            implementationTarget,
            false);
    MethodVisitor methodVisitor = mock(MethodVisitor.class);
    Implementation.Context implementationContext = mock(Implementation.Context.class);
    when(implementationContext.register(any(AuxiliaryType.class))).thenReturn(foo);
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(0));
    assertThat(size.getMaximalSize(), is(2));
    verify(implementationContext).register(any(AuxiliaryType.class));
    verifyNoMoreInteractions(implementationContext);
    verify(methodVisitor).visitTypeInsn(Opcodes.NEW, Type.getInternalName(Foo.class));
    verify(methodVisitor, times(2)).visitInsn(Opcodes.DUP);
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKESPECIAL,
            foo.getInternalName(),
            MethodDescription.CONSTRUCTOR_INTERNAL_NAME,
            foo.getDeclaredMethods().filter(isConstructor()).getOnly().getDescriptor(),
            false);
    verify(methodVisitor).visitFieldInsn(Opcodes.PUTFIELD,
            foo.getInternalName(),
            TypeProxy.INSTANCE_FIELD,
            Type.getDescriptor(Void.class));
    verify(methodVisitor).visitVarInsn(Opcodes.ALOAD, 0);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #26
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortIsConstructor() throws Exception {
    assertThat(ElementMatchers.isConstructor()
            .matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
    assertThat(ElementMatchers.isConstructor()
            .matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(true));
    assertThat(ElementMatchers.isConstructor()
            .matches(new MethodDescription.Latent.TypeInitializer(mock(TypeDescription.class))), is(false));
}
 
Example #27
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testTypeVariableOnMethodAnnotationTypeVariableBound() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Method method = createPlain()
            .merge(TypeManifestation.ABSTRACT)
            .defineMethod(FOO, void.class)
            .typeVariable(FOO).annotateTypeVariable(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE).build())
            .typeVariable(BAR, TypeDescription.Generic.Builder.rawType(Object.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE * 3).build()))
            .annotateTypeVariable(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE * 2).build())
            .withoutCode()
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getDeclaredMethod(FOO);
    assertThat(method.getTypeParameters().length, is(2));
    assertThat(method.getTypeParameters()[0].getBounds().length, is(1));
    assertThat(method.getTypeParameters()[0].getBounds()[0], is((Object) Object.class));
    assertThat(method.getTypeParameters()[1].getBounds().length, is(1));
    assertThat(method.getTypeParameters()[1].getBounds()[0], is((Object) Object.class));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(method.getTypeParameters()[0]).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(method.getTypeParameters()[0]).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(method.getTypeParameters()[1]).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(method.getTypeParameters()[1]).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE * 2));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(method.getTypeParameters()[1]).ofTypeVariableBoundType(0)
            .asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveTypeVariable(method.getTypeParameters()[1]).ofTypeVariableBoundType(0)
            .asList().ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(INTEGER_VALUE * 3));
}
 
Example #28
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMethod() throws Exception {
    assertThat(ElementMatchers.is(IsEqual.class.getDeclaredMethod(FOO))
            .matches(new MethodDescription.ForLoadedMethod(IsEqual.class.getDeclaredMethod(FOO))), is(true));
    assertThat(ElementMatchers.is(IsEqual.class.getDeclaredMethod(FOO))
            .matches(mock(MethodDescription.class)), is(false));
    assertThat(ElementMatchers.is(IsEqual.class.getDeclaredConstructor())
            .matches(new MethodDescription.ForLoadedConstructor(IsEqual.class.getDeclaredConstructor())), is(true));
    assertThat(ElementMatchers.is(IsEqual.class.getDeclaredConstructor())
            .matches(mock(MethodDescription.class)), is(false));
}
 
Example #29
Source File: ImplementationContextDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccessorMethodRegistration() throws Exception {
    Implementation.Context.Default implementationContext = new Implementation.Context.Default(instrumentedType,
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            typeInitializer,
            auxiliaryClassFileVersion);
    MethodDescription.InDefinedShape firstMethodDescription = implementationContext.registerAccessorFor(firstSpecialInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    assertThat(firstMethodDescription.getParameters(), is((ParameterList) new ParameterList.Explicit.ForTypes(firstMethodDescription, firstSpecialParameterType)));
    assertThat(firstMethodDescription.getReturnType(), is(firstSpecialReturnType));
    assertThat(firstMethodDescription.getInternalName(), startsWith(FOO));
    assertThat(firstMethodDescription.getModifiers(), is(accessorMethodModifiers));
    assertThat(firstMethodDescription.getExceptionTypes(), is(firstSpecialExceptionTypes));
    assertThat(implementationContext.registerAccessorFor(firstSpecialInvocation, MethodAccessorFactory.AccessType.DEFAULT), is(firstMethodDescription));
    when(secondSpecialMethod.isStatic()).thenReturn(true);
    MethodDescription.InDefinedShape secondMethodDescription = implementationContext.registerAccessorFor(secondSpecialInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    assertThat(secondMethodDescription.getParameters(), is((ParameterList) new ParameterList.Explicit.ForTypes(secondMethodDescription, secondSpecialParameterType)));
    assertThat(secondMethodDescription.getReturnType(), is(secondSpecialReturnType));
    assertThat(secondMethodDescription.getInternalName(), startsWith(BAR));
    assertThat(secondMethodDescription.getModifiers(), is(accessorMethodModifiers | Opcodes.ACC_STATIC));
    assertThat(secondMethodDescription.getExceptionTypes(), is(secondSpecialExceptionTypes));
    assertThat(implementationContext.registerAccessorFor(firstSpecialInvocation, MethodAccessorFactory.AccessType.DEFAULT), is(firstMethodDescription));
    assertThat(implementationContext.registerAccessorFor(secondSpecialInvocation, MethodAccessorFactory.AccessType.DEFAULT), is(secondMethodDescription));
    implementationContext.drain(drain, classVisitor, annotationValueFilterFactory);
    verify(classVisitor).visitMethod(eq(accessorMethodModifiers), Mockito.startsWith(FOO),
            eq("(" + BAZ + ")" + QUX), Mockito.<String>isNull(), aryEq(new String[]{FOO}));
    verify(classVisitor).visitMethod(eq(accessorMethodModifiers | Opcodes.ACC_STATIC), Mockito.startsWith(BAR),
            eq("(" + BAR + ")" + FOO), Mockito.<String>isNull(), aryEq(new String[]{BAZ}));
}
 
Example #30
Source File: MethodDelegationBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodBinding bind(Implementation.Target implementationTarget,
                          MethodDescription source,
                          TerminationHandler terminationHandler,
                          MethodInvoker methodInvoker,
                          Assigner assigner) {
    return MethodBinding.Illegal.INSTANCE;
}