net.bytebuddy.implementation.Implementation Java Examples

The following examples show how to use net.bytebuddy.implementation.Implementation. 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: RedefinitionDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
public void testDefaultInterfaceSubInterface() throws Exception {
    Class<?> interfaceType = Class.forName(DEFAULT_METHOD_INTERFACE);
    Class<?> dynamicInterfaceType = new ByteBuddy()
            .redefine(interfaceType)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(BAR), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    Class<?> dynamicClassType = new ByteBuddy()
            .subclass(dynamicInterfaceType)
            .make()
            .load(dynamicInterfaceType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(dynamicClassType.getMethod(FOO).invoke(dynamicClassType.getDeclaredConstructor().newInstance()), is((Object) BAR));
    assertThat(dynamicInterfaceType.getDeclaredMethods().length, is(1));
    assertThat(dynamicClassType.getDeclaredMethods().length, is(0));
}
 
Example #2
Source File: MethodDelegationBinder.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodBinding bind(Implementation.Target implementationTarget,
                          MethodDescription source,
                          TerminationHandler terminationHandler,
                          MethodInvoker methodInvoker,
                          Assigner assigner) {
    List<MethodBinding> targets = new ArrayList<MethodBinding>();
    for (Record record : records) {
        MethodBinding methodBinding = record.bind(implementationTarget, source, terminationHandler, methodInvoker, assigner);
        if (methodBinding.isValid()) {
            targets.add(methodBinding);
        }
    }
    if (targets.isEmpty()) {
        throw new IllegalArgumentException("None of " + records + " allows for delegation from " + source);
    }
    return bindingResolver.resolve(ambiguityResolver, source, targets);
}
 
Example #3
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod
) {
	methodVisitor.visitVarInsn( Opcodes.ALOAD, 0 );
	methodVisitor.visitVarInsn( Type.getType( persistentField.getType().asErasure().getDescriptor() ).getOpcode( Opcodes.ILOAD ), 1 );
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + persistentField.getName(),
			Type.getMethodDescriptor( Type.getType( void.class ), Type.getType( persistentField.getType().asErasure().getDescriptor() ) ),
			false
	);
	methodVisitor.visitInsn( Opcodes.RETURN );
	return new Size( 1 + persistentField.getType().getStackSize().getSize(), instrumentedMethod.getStackSize() );
}
 
Example #4
Source File: SimpleExceptionHandler.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext,
                  MethodDescription instrumentedMethod) {

    final Label startTryBlock = new Label();
    final Label endTryBlock = new Label();
    final Label startCatchBlock = new Label();

    final StackManipulation preTriggerAppender = preTrigger(startTryBlock, endTryBlock, startCatchBlock);
    final StackManipulation postTriggerAppender = postTrigger(endTryBlock, startCatchBlock);

    final StackManipulation delegate = new StackManipulation.Compound(
            preTriggerAppender, exceptionThrowingAppender, postTriggerAppender, exceptionHandlerAppender
    );

    final StackManipulation.Size operandStackSize = delegate.apply(methodVisitor, implementationContext);
    return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + newLocalVariablesCount);
}
 
Example #5
Source File: StackManipulationCompoundTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplication() throws Exception {
    MethodVisitor methodVisitor = mock(MethodVisitor.class);
    Implementation.Context implementationContext = mock(Implementation.Context.class);
    when(first.apply(methodVisitor, implementationContext)).thenReturn(new StackManipulation.Size(2, 3));
    when(second.apply(methodVisitor, implementationContext)).thenReturn(new StackManipulation.Size(2, 3));
    StackManipulation.Size size = new StackManipulation.Compound(first, second).apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(4));
    assertThat(size.getMaximalSize(), is(5));
    verify(first).apply(methodVisitor, implementationContext);
    verifyNoMoreInteractions(first);
    verify(second).apply(methodVisitor, implementationContext);
    verifyNoMoreInteractions(second);
    verifyZeroInteractions(methodVisitor);
    verifyZeroInteractions(implementationContext);
}
 
Example #6
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new Byte Buddy instance.
 *
 * @param classFileVersion             The class file version to use for types that are not based on an existing class file.
 * @param namingStrategy               The naming strategy to use.
 * @param auxiliaryTypeNamingStrategy  The naming strategy to use for naming auxiliary types.
 * @param annotationValueFilterFactory The annotation value filter factory to use.
 * @param annotationRetention          The annotation retention strategy to use.
 * @param implementationContextFactory The implementation context factory to use.
 * @param methodGraphCompiler          The method graph compiler to use.
 * @param instrumentedTypeFactory      The instrumented type factory to use.
 * @param typeValidation               Determines if a type should be explicitly validated.
 * @param visibilityBridgeStrategy     The visibility bridge strategy to apply.
 * @param classWriterStrategy          The class writer strategy to use.
 * @param ignoredMethods               A matcher for identifying methods that should be excluded from instrumentation.
 */
protected ByteBuddy(ClassFileVersion classFileVersion,
                    NamingStrategy namingStrategy,
                    AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy,
                    AnnotationValueFilter.Factory annotationValueFilterFactory,
                    AnnotationRetention annotationRetention,
                    Implementation.Context.Factory implementationContextFactory,
                    MethodGraph.Compiler methodGraphCompiler,
                    InstrumentedType.Factory instrumentedTypeFactory,
                    TypeValidation typeValidation,
                    VisibilityBridgeStrategy visibilityBridgeStrategy,
                    ClassWriterStrategy classWriterStrategy,
                    LatentMatcher<? super MethodDescription> ignoredMethods) {
    this.classFileVersion = classFileVersion;
    this.namingStrategy = namingStrategy;
    this.auxiliaryTypeNamingStrategy = auxiliaryTypeNamingStrategy;
    this.annotationValueFilterFactory = annotationValueFilterFactory;
    this.annotationRetention = annotationRetention;
    this.implementationContextFactory = implementationContextFactory;
    this.methodGraphCompiler = methodGraphCompiler;
    this.instrumentedTypeFactory = instrumentedTypeFactory;
    this.typeValidation = typeValidation;
    this.visibilityBridgeStrategy = visibilityBridgeStrategy;
    this.classWriterStrategy = classWriterStrategy;
    this.ignoredMethods = ignoredMethods;
}
 
Example #7
Source File: TypeConstantAdjustmentTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstrumentationModernClassFile() throws Exception {
    ClassVisitor classVisitor = TypeConstantAdjustment.INSTANCE.wrap(mock(TypeDescription.class),
            this.classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED);
    classVisitor.visit(ClassFileVersion.JAVA_V5.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    assertThat(classVisitor.visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ}), is(methodVisitor));
    verify(this.classVisitor).visit(ClassFileVersion.JAVA_V5.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verify(this.classVisitor).visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verifyNoMoreInteractions(this.classVisitor);
    verifyZeroInteractions(methodVisitor);
}
 
Example #8
Source File: MemberSubstitution.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) {
    typePool = typePoolResolver.resolve(instrumentedType, instrumentedMethod, typePool);
    return new SubstitutingMethodVisitor(methodVisitor,
            instrumentedType,
            instrumentedMethod,
            methodGraphCompiler,
            strict,
            replacementFactory.make(instrumentedType, instrumentedMethod, typePool),
            implementationContext,
            typePool,
            implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V11));
}
 
Example #9
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 #10
Source File: MethodConstant.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription auxiliaryType = implementationContext.register(PrivilegedMemberLookupAction.of(methodDescription));
    return new Compound(
            TypeCreation.of(auxiliaryType),
            Duplication.SINGLE,
            ClassConstant.of(methodDescription.getDeclaringType()),
            methodName,
            ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
                    .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())),
            MethodInvocation.invoke(auxiliaryType.getDeclaredMethods().filter(isConstructor()).getOnly()),
            MethodInvocation.invoke(DO_PRIVILEGED),
            TypeCasting.to(TypeDescription.ForLoadedType.of(methodDescription.isConstructor()
                    ? Constructor.class
                    : Method.class))
    ).apply(methodVisitor, implementationContext);
}
 
Example #11
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new dispatching visitor.
 *
 * @param classVisitor          The underlying class visitor.
 * @param instrumentedType      The instrumented type.
 * @param implementationContext The implementation context to use.
 * @param typePool              The type pool to use.
 * @param methods               The methods that are declared by the instrumented type or virtually inherited.
 * @param writerFlags           The ASM {@link org.objectweb.asm.ClassWriter} flags to consider.
 * @param readerFlags           The ASM {@link org.objectweb.asm.ClassReader} flags to consider.
 */
protected DispatchingVisitor(ClassVisitor classVisitor,
                             TypeDescription instrumentedType,
                             Implementation.Context implementationContext,
                             TypePool typePool,
                             Map<String, MethodDescription> methods,
                             int writerFlags,
                             int readerFlags) {
    super(OpenedClassReader.ASM_API, classVisitor);
    this.instrumentedType = instrumentedType;
    this.implementationContext = implementationContext;
    this.typePool = typePool;
    this.methods = methods;
    this.writerFlags = writerFlags;
    this.readerFlags = readerFlags;
}
 
Example #12
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 #13
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisableClassFormatChanges() throws Exception {
    assertThat(new AgentBuilder.Default().disableClassFormatChanges(), hasPrototype(new AgentBuilder.Default(new ByteBuddy()
            .with(Implementation.Context.Disabled.Factory.INSTANCE))
            .with(AgentBuilder.InitializationStrategy.NoOp.INSTANCE)
            .with(AgentBuilder.TypeStrategy.Default.REDEFINE_FROZEN)));
}
 
Example #14
Source File: AbstractArrayFactoryTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
private void defineComponentType(Class<?> type) {
    when(componentType.isPrimitive()).thenReturn(type.isPrimitive());
    when(componentType.represents(type)).thenReturn(true);
    when(rawComponentType.getInternalName()).thenReturn(Type.getInternalName(type));
    when(componentType.getStackSize()).thenReturn(StackSize.of(type));
    when(stackManipulation.apply(any(MethodVisitor.class), any(Implementation.Context.class))).thenReturn(StackSize.of(type).toIncreasingSize());
}
 
Example #15
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 #16
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 #17
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public MethodVisitor wrap(
		TypeDescription instrumentedType,
		MethodDescription instrumentedMethod,
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		TypePool typePool,
		int writerFlags,
		int readerFlags) {
	return new MethodVisitor( Opcodes.ASM5, methodVisitor ) {
		@Override
		public void visitFieldInsn(int opcode, String owner, String name, String desc) {
			if ( isEnhanced( owner, name, desc ) ) {
				switch ( opcode ) {
					case Opcodes.GETFIELD:
						methodVisitor.visitMethodInsn(
								Opcodes.INVOKEVIRTUAL,
								owner,
								EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + name,
								"()" + desc,
								false
						);
						return;
					case Opcodes.PUTFIELD:
						methodVisitor.visitMethodInsn(
								Opcodes.INVOKEVIRTUAL,
								owner,
								EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + name,
								"(" + desc + ")V",
								false
						);
						return;
				}
			}
			super.visitFieldInsn( opcode, owner, name, desc );
		}
	};
}
 
Example #18
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBridgeMethodCreation() throws Exception {
    Class<?> dynamicType = create(BridgeRetention.Inner.class)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertEquals(String.class, dynamicType.getDeclaredMethod(FOO).getReturnType());
    assertThat(dynamicType.getDeclaredMethod(FOO).getGenericReturnType(), is((Type) String.class));
    BridgeRetention<String> bridgeRetention = (BridgeRetention<String>) dynamicType.getDeclaredConstructor().newInstance();
    assertThat(bridgeRetention.foo(), is(FOO));
    bridgeRetention.assertZeroCalls();
}
 
Example #19
Source File: TypeProxyCreationTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllLegal() 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);
    TypeDescription dynamicType = new TypeProxy(foo,
            implementationTarget,
            invocationFactory,
            true,
            false)
            .make(BAR, ClassFileVersion.ofThisVm(), methodAccessorFactory)
            .getTypeDescription();
    assertThat(dynamicType.getModifiers(), is(modifiers));
    assertThat(dynamicType.getSuperClass().asErasure(), is(foo));
    assertThat(dynamicType.getInterfaces(), is((TypeList.Generic) new TypeList.Generic.Empty()));
    assertThat(dynamicType.getName(), is(BAR));
    assertThat(dynamicType.getDeclaredMethods().size(), is(2));
    assertThat(dynamicType.isAssignableTo(Serializable.class), is(false));
    verify(methodAccessorFactory, times(fooMethods.size())).registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    for (MethodDescription methodDescription : fooMethods) {
        verify(invocationFactory).invoke(implementationTarget, foo, methodDescription);
    }
    verifyNoMoreInteractions(invocationFactory);
    verify(specialMethodInvocation, times(fooMethods.size())).isValid();
    verifyNoMoreInteractions(specialMethodInvocation);
}
 
Example #20
Source File: MethodDelegationBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnored() throws Exception {
    assertThat(MethodDelegationBinder.Record.Illegal.INSTANCE.bind(mock(Implementation.Target.class),
            mock(MethodDescription.class),
            mock(MethodDelegationBinder.TerminationHandler.class),
            mock(MethodDelegationBinder.MethodInvoker.class),
            mock(Assigner.class)).isValid(), is(false));
}
 
Example #21
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    MethodDescription.InDefinedShape proxyMethod = methodAccessorFactory.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    return new StackManipulation.Compound(
            MethodVariableAccess.loadThis(),
            fieldLoadingInstruction,
            MethodVariableAccess.allArgumentsOf(instrumentedMethod).asBridgeOf(proxyMethod),
            MethodInvocation.invoke(proxyMethod),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
}
 
Example #22
Source File: FieldAccess.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    methodVisitor.visitFieldInsn(getOpcode(),
            fieldDescription.getDeclaringType().getInternalName(),
            fieldDescription.getInternalName(),
            fieldDescription.getDescriptor());
    return resolveSize(fieldDescription.getType().getStackSize());
}
 
Example #23
Source File: PropertyAccessorCollector.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext) {

    final List<StackManipulation> operations = new ArrayList<StackManipulation>();
    operations.add(loadLocalVar()); // load local for cast bean

    final AnnotatedMember member = prop.getMember();

    operations.add(invocationOperation(member, beanClassDescription));
    operations.add(methodReturn);

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example #24
Source File: TargetMethodAnnotationDrivenBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ParameterBinding<?> bind(MethodDescription source, Implementation.Target implementationTarget, Assigner assigner) {
    return Argument.Binder.INSTANCE.bind(AnnotationDescription.ForLoadedAnnotation.<Argument>of(new DefaultArgument(target.getIndex())),
            source,
            target,
            implementationTarget,
            assigner,
            typing);
}
 
Example #25
Source File: RebaseImplementationTarget.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Implementation.SpecialMethodInvocation withCheckedCompatibilityTo(MethodDescription.TypeToken token) {
    if (methodDescription.asTypeToken().equals(new MethodDescription.TypeToken(token.getReturnType(),
            CompoundList.of(token.getParameterTypes(), prependedParameters)))) {
        return this;
    } else {
        return Illegal.INSTANCE;
    }
}
 
Example #26
Source File: ByteArrayClassLoaderChildFirstTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    return new ClassRemapper(OpenedClassReader.ASM_API, classVisitor, new SimpleRemapper(oldName, newName)) {
        /* only anonymous to define usage of Byte Buddy specific API version */
    };
}
 
Example #27
Source File: PropertyMutatorCollector.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private <T extends OptimizedSettableBeanProperty<T>> DynamicType.Builder<?> _addSetters(
        DynamicType.Builder<?> builder, List<T> props, String methodName, MethodVariableAccess beanValueAccess) {

    return builder.method(named(methodName))
                  .intercept(
                          new Implementation.Simple(
                                  new MethodAppender<T>(beanClassDefinition, props, beanValueAccess)
                          )
                  );
}
 
Example #28
Source File: ClassConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    if (implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V5) && typeDescription.isVisibleTo(implementationContext.getInstrumentedType())) {
        methodVisitor.visitLdcInsn(Type.getType(typeDescription.getDescriptor()));
    } else {
        methodVisitor.visitLdcInsn(typeDescription.getName());
        methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;", false);
    }
    return SIZE;
}
 
Example #29
Source File: DecoratingDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecoration() throws Exception {
    Object instance = new ByteBuddy()
            .decorate(Foo.class)
            .annotateType(AnnotationDescription.Builder.ofType(Qux.class).build())
            .ignoreAlso(new LatentMatcher.Resolved<MethodDescription>(none()))
            .visit(new AsmVisitorWrapper.ForDeclaredMethods().method(named(FOO), new AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper() {
                public MethodVisitor wrap(TypeDescription instrumentedType,
                                          MethodDescription instrumentedMethod,
                                          MethodVisitor methodVisitor,
                                          Implementation.Context implementationContext,
                                          TypePool typePool,
                                          int writerFlags,
                                          int readerFlags) {
                    return new MethodVisitor(OpenedClassReader.ASM_API, methodVisitor) {
                        public void visitLdcInsn(Object value) {
                            if (FOO.equals(value)) {
                                value = BAR;
                            }
                            super.visitLdcInsn(value);
                        }
                    };
                }
            }))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getConstructor()
            .newInstance();
    assertThat(instance.getClass().getMethod(FOO).invoke(instance), is((Object) BAR));
    assertThat(instance.getClass().isAnnotationPresent(Bar.class), is(true));
    assertThat(instance.getClass().isAnnotationPresent(Qux.class), is(true));
}
 
Example #30
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Implementation fieldReader(FieldDescription enhancedField) {
	if ( !enhancementContext.hasLazyLoadableAttributes( managedCtClass ) || !enhancementContext.isLazyLoadable( enhancedField ) ) {
		if ( enhancedField.getDeclaringType().asErasure().equals( managedCtClass ) ) {
			return FieldAccessor.ofField( enhancedField.getName() ).in( enhancedField.getDeclaringType().asErasure() );
		}
		else {
			return new Implementation.Simple( new FieldMethodReader( managedCtClass, enhancedField ) );
		}
	}
	else {
		return new Implementation.Simple( FieldReaderAppender.of( managedCtClass, enhancedField ) );
	}
}