net.bytebuddy.implementation.bytecode.ByteCodeAppender Java Examples

The following examples show how to use net.bytebuddy.implementation.bytecode.ByteCodeAppender. 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: TypeWriterMethodPoolRecordTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(methodDescription.getInternalName()).thenReturn(FOO);
    when(methodDescription.getDescriptor()).thenReturn(BAR);
    when(methodDescription.getGenericSignature()).thenReturn(QUX);
    when(methodDescription.getExceptionTypes()).thenReturn(exceptionTypes);
    when(methodDescription.getActualModifiers(anyBoolean(), any(Visibility.class))).thenReturn(MODIFIERS);
    when(exceptionTypes.asErasures()).thenReturn(rawExceptionTypes);
    when(rawExceptionTypes.toInternalNames()).thenReturn(new String[]{BAZ});
    when(classVisitor.visitMethod(MODIFIERS, FOO, BAR, QUX, new String[]{BAZ})).thenReturn(methodVisitor);
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Explicit<ParameterDescription>(parameterDescription));
    when(parameterDescription.getName()).thenReturn(FOO);
    when(parameterDescription.getModifiers()).thenReturn(MODIFIERS);
    when(methodVisitor.visitAnnotationDefault()).thenReturn(annotationVisitor);
    when(byteCodeAppender.apply(methodVisitor, implementationContext, methodDescription))
            .thenReturn(new ByteCodeAppender.Size(ONE, TWO));
    when(otherAppender.apply(methodVisitor, implementationContext, methodDescription))
            .thenReturn(new ByteCodeAppender.Size(ONE * MULTIPLIER, TWO * MULTIPLIER));
    when(annotationValueFilterFactory.on(methodDescription)).thenReturn(annotationValueFilter);
    when(methodDescription.getVisibility()).thenReturn(Visibility.PUBLIC);
}
 
Example #2
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    if (implementationTarget.getInstrumentedType().isInterface()) {
        throw new IllegalStateException("Cannot implement meaningful equals method for " + implementationTarget.getInstrumentedType());
    }
    List<FieldDescription.InDefinedShape> fields = new ArrayList<FieldDescription.InDefinedShape>(implementationTarget.getInstrumentedType()
            .getDeclaredFields()
            .filter(not(isStatic().or(ignored))));
    Collections.sort(fields, comparator);
    return new Appender(implementationTarget.getInstrumentedType(), new StackManipulation.Compound(
            superClassCheck.resolve(implementationTarget.getInstrumentedType()),
            MethodVariableAccess.loadThis(),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            ConditionalReturn.onIdentity().returningTrue(),
            typeCompatibilityCheck.resolve(implementationTarget.getInstrumentedType())
    ), fields, nonNullable);
}
 
Example #3
Source File: InstrumentedType.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public WithFlexibleName withInitializer(ByteCodeAppender byteCodeAppender) {
    return new Default(name,
            modifiers,
            superClass,
            typeVariables,
            interfaceTypes,
            fieldTokens,
            methodTokens,
            recordComponentTokens,
            annotationDescriptions,
            typeInitializer.expandWith(byteCodeAppender),
            loadedTypeInitializer,
            declaringType,
            enclosingMethod,
            enclosingType,
            declaredTypes,
            anonymousClass,
            localClass,
            record,
            nestHost,
            nestMembers);
}
 
Example #4
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Blueprint method that for applying the actual implementation.
 *
 * @param methodVisitor           The method visitor to which the implementation is applied to.
 * @param implementationContext   The implementation context for the given implementation.
 * @param instrumentedMethod      The instrumented method that is target of the implementation.
 * @param fixedValueType          A description of the type of the fixed value that is loaded by the
 *                                {@code valueLoadingInstruction}.
 * @param valueLoadingInstruction A stack manipulation that represents the loading of the fixed value onto the
 *                                operand stack.
 * @return A representation of the stack and variable array sized that are required for this implementation.
 */
protected ByteCodeAppender.Size apply(MethodVisitor methodVisitor,
                                      Context implementationContext,
                                      MethodDescription instrumentedMethod,
                                      TypeDescription.Generic fixedValueType,
                                      StackManipulation valueLoadingInstruction) {
    StackManipulation assignment = assigner.assign(fixedValueType, instrumentedMethod.getReturnType(), typing);
    if (!assignment.isValid()) {
        throw new IllegalArgumentException("Cannot return value of type " + fixedValueType + " for " + instrumentedMethod);
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            valueLoadingInstruction,
            assignment,
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new ByteCodeAppender.Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #5
Source File: InvocationHandlerAdapter.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Applies an implementation that delegates to a invocation handler.
 *
 * @param methodVisitor         The method visitor for writing the byte code to.
 * @param implementationContext The implementation context for the current implementation.
 * @param instrumentedMethod    The method that is instrumented.
 * @param preparingManipulation A stack manipulation that applies any preparation to the operand stack.
 * @param fieldDescription      The field that contains the value for the invocation handler.
 * @return The size of the applied assignment.
 */
protected ByteCodeAppender.Size apply(MethodVisitor methodVisitor,
                                      Context implementationContext,
                                      MethodDescription instrumentedMethod,
                                      StackManipulation preparingManipulation,
                                      FieldDescription fieldDescription) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("It is not possible to apply an invocation handler onto the static method " + instrumentedMethod);
    }
    MethodConstant.CanCache methodConstant = privileged
            ? MethodConstant.ofPrivileged(instrumentedMethod.asDefined())
            : MethodConstant.of(instrumentedMethod.asDefined());
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            preparingManipulation,
            FieldAccess.forField(fieldDescription).read(),
            MethodVariableAccess.loadThis(),
            cached ? methodConstant.cached() : methodConstant,
            ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(argumentValuesOf(instrumentedMethod)),
            MethodInvocation.invoke(INVOCATION_HANDLER_TYPE.getDeclaredMethods().getOnly()),
            assigner.assign(TypeDescription.Generic.OBJECT, instrumentedMethod.getReturnType(), Assigner.Typing.DYNAMIC),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new ByteCodeAppender.Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #6
Source File: TypeWriterDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeInitializerOnRebasedInterfaceWithInitializer() throws Exception {
    assertThat(new ByteBuddy()
            .makeInterface()
            .initializer(new ByteCodeAppender.Simple())
            .invokable(isTypeInitializer())
            .intercept(StubMethod.INSTANCE)
            .make(), notNullValue(DynamicType.class));
}
 
Example #7
Source File: FieldWriterAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static ByteCodeAppender of(TypeDescription managedCtClass, FieldDescription persistentField) {
	if ( !persistentField.isVisibleTo( managedCtClass ) ) {
		return new MethodDispatching( managedCtClass, persistentField.asDefined() );
	}
	else {
		return new FieldWriting( managedCtClass, persistentField.asDefined() );
	}
}
 
Example #8
Source File: CreatorOptimizer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
protected byte[] generateOptimized(ClassName baseName, Constructor<?> ctor, Method factory) {
    final String tmpClassName = baseName.getSlashedTemplate();
    final DynamicType.Builder<?> builder =
            new ByteBuddy(ClassFileVersion.JAVA_V5)
                    .with(TypeValidation.DISABLED)
                    .subclass(OptimizedValueInstantiator.class) //default strategy ensures that all constructors are created
                    .name(tmpClassName)
                    .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
                    .method(named("with"))
                    .intercept(
                            //call the constructor of this method that takes a single StdValueInstantiator arg
                            //the required arg is in the position 1 of the method's local variables
                            new Implementation.Simple(
                                    new ByteCodeAppender.Simple(
                                            new ConstructorCallStackManipulation.OfInstrumentedType.OneArg(
                                                    REFERENCE.loadFrom(1)
                                            ),
                                            MethodReturn.REFERENCE
                                    )
                            )

                    )
                    .method(named("createUsingDefault"))
                    .intercept(
                            new SimpleExceptionHandler(
                                    creatorInvokerStackManipulation(ctor, factory),
                                    creatorExceptionHandlerStackManipulation(),
                                    Exception.class,
                                    1 //we added a new local variable in the catch block
                            )
                    );


    return builder.make().getBytes();
}
 
Example #9
Source File: InvocationHandlerAdapter.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    FieldLocator.Resolution resolution = fieldLocatorFactory.make(implementationTarget.getInstrumentedType()).locate(fieldName);
    if (!resolution.isResolved()) {
        throw new IllegalStateException("Could not find a field named '" + fieldName + "' for " + implementationTarget.getInstrumentedType());
    } else if (!resolution.getField().getType().asErasure().isAssignableTo(InvocationHandler.class)) {
        throw new IllegalStateException("Field " + resolution.getField() + " does not declare a type that is assignable to invocation handler");
    }
    return new Appender(resolution.getField());
}
 
Example #10
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    StringBuilder stringBuilder = new StringBuilder();
    List<Object> methodHandles = new ArrayList<Object>(implementationTarget.getInstrumentedType().getRecordComponents().size());
    for (RecordComponentDescription.InDefinedShape recordComponent : implementationTarget.getInstrumentedType().getRecordComponents()) {
        if (stringBuilder.length() > 0) {
            stringBuilder.append(";");
        }
        stringBuilder.append(recordComponent.getActualName());
        methodHandles.add(JavaConstant.MethodHandle.ofGetter(implementationTarget.getInstrumentedType().getDeclaredFields()
                .filter(named(recordComponent.getActualName()))
                .getOnly()).asConstantPoolValue());
    }
    return new ByteCodeAppender.Simple(MethodVariableAccess.loadThis(),
            stackManipulation,
            MethodInvocation.invoke(new MethodDescription.Latent(JavaType.OBJECT_METHODS.getTypeStub(), new MethodDescription.Token("bootstrap",
                    Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
                    TypeDescription.Generic.OBJECT,
                    Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub().asGenericType(),
                            TypeDescription.STRING.asGenericType(),
                            JavaType.TYPE_DESCRIPTOR.getTypeStub().asGenericType(),
                            TypeDescription.CLASS.asGenericType(),
                            TypeDescription.STRING.asGenericType(),
                            TypeDescription.ArrayProjection.of(JavaType.METHOD_HANDLE.getTypeStub()).asGenericType())))).dynamic(name,
                    returnType,
                    CompoundList.of(implementationTarget.getInstrumentedType(), arguments),
                    CompoundList.of(Arrays.asList(org.objectweb.asm.Type.getType(implementationTarget.getInstrumentedType().getDescriptor()), stringBuilder.toString()), methodHandles)),
            MethodReturn.of(returnType));
}
 
Example #11
Source File: Implementation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    ByteCodeAppender[] byteCodeAppender = new ByteCodeAppender[implementations.size()];
    int index = 0;
    for (Implementation implementation : implementations) {
        byteCodeAppender[index++] = implementation.appender(implementationTarget);
    }
    return new ByteCodeAppender.Compound(byteCodeAppender);
}
 
Example #12
Source File: Implementation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    ByteCodeAppender[] byteCodeAppender = new ByteCodeAppender[implementations.size() + 1];
    int index = 0;
    for (Implementation implementation : implementations) {
        byteCodeAppender[index++] = implementation.appender(implementationTarget);
    }
    byteCodeAppender[index] = composable.appender(implementationTarget);
    return new ByteCodeAppender.Compound(byteCodeAppender);
}
 
Example #13
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    ImplementationDelegate.Compiled compiled = implementationDelegate.compile(implementationTarget.getInstrumentedType());
    return new Appender(implementationTarget,
            new MethodDelegationBinder.Processor(compiled.getRecords(), ambiguityResolver, bindingResolver),
            terminationHandler,
            assigner,
            compiled);
}
 
Example #14
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic() || !instrumentedType.isAssignableTo(instrumentedMethod.getReturnType().asErasure())) {
        throw new IllegalStateException("Cannot return 'this' from " + instrumentedMethod);
    }
    return new ByteCodeAppender.Simple(
            MethodVariableAccess.loadThis(),
            MethodReturn.REFERENCE
    ).apply(methodVisitor, implementationContext, instrumentedMethod);
}
 
Example #15
Source File: FieldReaderAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static ByteCodeAppender of(TypeDescription managedCtClass, FieldDescription persistentField) {
	if ( !persistentField.isVisibleTo( managedCtClass ) ) {
		return new MethodDispatching( managedCtClass, persistentField );
	}
	else {
		return new FieldWriting( managedCtClass, persistentField );
	}
}
 
Example #16
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTypeInitializerDouble() throws Exception {
    InstrumentedType instrumentedType = makePlainInstrumentedType();
    assertThat(instrumentedType.getDeclaredFields().size(), is(0));
    ByteCodeAppender first = mock(ByteCodeAppender.class), second = mock(ByteCodeAppender.class);
    MethodDescription methodDescription = mock(MethodDescription.class);
    when(first.apply(methodVisitor, implementationContext, methodDescription)).thenReturn(new ByteCodeAppender.Size(0, 0));
    when(second.apply(methodVisitor, implementationContext, methodDescription)).thenReturn(new ByteCodeAppender.Size(0, 0));
    instrumentedType = instrumentedType.withInitializer(first).withInitializer(second);
    TypeInitializer typeInitializer = instrumentedType.getTypeInitializer();
    assertThat(typeInitializer.isDefined(), is(true));
    typeInitializer.apply(methodVisitor, implementationContext, methodDescription);
    verify(first).apply(methodVisitor, implementationContext, methodDescription);
    verify(second).apply(methodVisitor, implementationContext, methodDescription);
}
 
Example #17
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTypeInitializerSingle() throws Exception {
    InstrumentedType instrumentedType = makePlainInstrumentedType();
    assertThat(instrumentedType.getDeclaredFields().size(), is(0));
    ByteCodeAppender byteCodeAppender = mock(ByteCodeAppender.class);
    instrumentedType = instrumentedType.withInitializer(byteCodeAppender);
    TypeInitializer typeInitializer = instrumentedType.getTypeInitializer();
    assertThat(typeInitializer.isDefined(), is(true));
    MethodDescription methodDescription = mock(MethodDescription.class);
    typeInitializer.apply(methodVisitor, implementationContext, methodDescription);
    verify(byteCodeAppender).apply(methodVisitor, implementationContext, methodDescription);
}
 
Example #18
Source File: TypeWriterMethodPoolRecordTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkippedMethodCannotBePrepended() throws Exception {
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.OBJECT);
    assertThat(new TypeWriter.MethodPool.Record.ForNonImplementedMethod(methodDescription).prepend(byteCodeAppender), hasPrototype((TypeWriter.MethodPool.Record)
            new TypeWriter.MethodPool.Record.ForDefinedMethod.WithBody(methodDescription,
                    new ByteCodeAppender.Compound(byteCodeAppender, new ByteCodeAppender.Simple(DefaultValue.REFERENCE, MethodReturn.REFERENCE)))));
}
 
Example #19
Source File: ImplementationContextDefaultOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testDefaultContext() throws Exception {
    new Implementation.Context.Default.DelegationRecord(mock(MethodDescription.InDefinedShape.class), Visibility.PACKAGE_PRIVATE) {
        public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
            throw new AssertionError();
        }

        @Override
        protected Implementation.Context.Default.DelegationRecord with(MethodAccessorFactory.AccessType accessType) {
            throw new AssertionError();
        }
    }.prepend(mock(ByteCodeAppender.class));
}
 
Example #20
Source File: ImplementationContextDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDrainFieldCacheEntries() throws Exception {
    Implementation.Context.ExtractableView implementationContext = new Implementation.Context.Default(instrumentedType,
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            typeInitializer,
            auxiliaryClassFileVersion);
    FieldDescription firstField = implementationContext.cache(firstFieldValue, firstRawFieldType);
    assertThat(implementationContext.cache(firstFieldValue, firstRawFieldType), is(firstField));
    FieldDescription secondField = implementationContext.cache(secondFieldValue, secondRawFieldType);
    assertThat(implementationContext.cache(secondFieldValue, secondRawFieldType), is(secondField));
    assertThat(firstField.getName(), not(secondField.getName()));
    when(typeInitializer.expandWith(any(ByteCodeAppender.class))).thenReturn(otherTypeInitializer);
    when(otherTypeInitializer.expandWith(any(ByteCodeAppender.class))).thenReturn(thirdTypeInitializer);
    when(thirdTypeInitializer.isDefined()).thenReturn(true);
    implementationContext.drain(drain, classVisitor, annotationValueFilterFactory);
    verify(classVisitor).visitField(eq(cacheFieldModifiers),
            Mockito.startsWith(Implementation.Context.Default.FIELD_CACHE_PREFIX),
            eq(BAR),
            Mockito.<String>isNull(),
            Mockito.isNull());
    verify(classVisitor).visitField(eq(cacheFieldModifiers),
            Mockito.startsWith(Implementation.Context.Default.FIELD_CACHE_PREFIX),
            eq(QUX),
            Mockito.<String>isNull(),
            Mockito.isNull());
    verify(typeInitializer).expandWith(any(ByteCodeAppender.class));
    verify(otherTypeInitializer).expandWith(any(ByteCodeAppender.class));
}
 
Example #21
Source File: TypeInitializerTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoneThrowsExceptionOnApplication() throws Exception {
    ByteCodeAppender.Size size = TypeInitializer.None.INSTANCE.apply(methodVisitor, implementationContext, methodDescription);
    assertThat(size.getOperandStackSize(), is(0));
    assertThat(size.getLocalVariableSize(), is(0));
    verifyZeroInteractions(methodDescription);
}
 
Example #22
Source File: AgentBuilderInitializationStrategySelfInjectionDispatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(builder.initializer((any(ByteCodeAppender.class)))).thenReturn((DynamicType.Builder) appendedBuilder);
    when(injectionStrategy.resolve(Qux.class.getClassLoader(), Qux.class.getProtectionDomain())).thenReturn(classInjector);
    when(dynamicType.getTypeDescription()).thenReturn(instrumented);
    Map<TypeDescription, byte[]> auxiliaryTypes = new HashMap<TypeDescription, byte[]>();
    auxiliaryTypes.put(dependent, FOO);
    auxiliaryTypes.put(independent, BAR);
    when(dynamicType.getAuxiliaryTypes()).thenReturn(auxiliaryTypes);
    Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>();
    loadedTypeInitializers.put(instrumented, instrumentedInitializer);
    loadedTypeInitializers.put(dependent, dependentInitializer);
    loadedTypeInitializers.put(independent, independentInitializer);
    when(dynamicType.getLoadedTypeInitializers()).thenReturn(loadedTypeInitializers);
    when(instrumented.getName()).thenReturn(Qux.class.getName());
    when(classInjector.inject(any(Map.class))).then(new Answer<Map<TypeDescription, Class<?>>>() {
        public Map<TypeDescription, Class<?>> answer(InvocationOnMock invocationOnMock) throws Throwable {
            Map<TypeDescription, Class<?>> loaded = new HashMap<TypeDescription, Class<?>>();
            for (TypeDescription typeDescription : ((Map<TypeDescription, byte[]>) invocationOnMock.getArguments()[0]).keySet()) {
                if (typeDescription.equals(dependent)) {
                    loaded.put(dependent, Foo.class);
                } else if (typeDescription.equals(independent)) {
                    loaded.put(independent, Bar.class);
                } else {
                    throw new AssertionError();
                }
            }
            return loaded;
        }
    });
    Annotation eagerAnnotation = mock(AuxiliaryType.SignatureRelevant.class);
    when(eagerAnnotation.annotationType()).thenReturn((Class) AuxiliaryType.SignatureRelevant.class);
    when(independent.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(eagerAnnotation));
    when(dependent.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(instrumentedInitializer.isAlive()).thenReturn(true);
}
 
Example #23
Source File: NexusAccessor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
    try {
        return new ByteCodeAppender.Simple(new StackManipulation.Compound(
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ClassLoader.class.getMethod("getSystemClassLoader"))),
                new TextConstant(Nexus.class.getName()),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ClassLoader.class.getMethod("loadClass", String.class))),
                new TextConstant("initialize"),
                ArrayFactory.forType(TypeDescription.Generic.CLASS)
                        .withValues(Arrays.asList(
                                ClassConstant.of(TypeDescription.CLASS),
                                ClassConstant.of(TypeDescription.ForLoadedType.of(int.class)))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Class.class.getMethod("getMethod", String.class, Class[].class))),
                NullConstant.INSTANCE,
                ArrayFactory.forType(TypeDescription.Generic.OBJECT)
                        .withValues(Arrays.asList(
                                ClassConstant.of(instrumentedMethod.getDeclaringType().asErasure()),
                                new StackManipulation.Compound(
                                        IntegerConstant.forValue(identification),
                                        MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Integer.class.getMethod("valueOf", int.class)))))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Method.class.getMethod("invoke", Object.class, Object[].class))),
                Removal.SINGLE
        )).apply(methodVisitor, implementationContext, instrumentedMethod);
    } catch (NoSuchMethodException exception) {
        throw new IllegalStateException("Cannot locate method", exception);
    }
}
 
Example #24
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.getReturnType().isPrimitive()) {
        throw new IllegalStateException("Cannot return null from " + instrumentedMethod);
    }
    return new ByteCodeAppender.Simple(
            NullConstant.INSTANCE,
            MethodReturn.REFERENCE
    ).apply(methodVisitor, implementationContext, instrumentedMethod);
}
 
Example #25
Source File: AdviceDeadCodeTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
public ByteCodeAppender appender(Target implementationTarget) {
    return this;
}
 
Example #26
Source File: AdviceDeadCodeTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
public ByteCodeAppender appender(Target implementationTarget) {
    return this;
}
 
Example #27
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
public ByteCodeAppender appender(Target implementationTarget) {
    return SumMethod.INSTANCE;
}
 
Example #28
Source File: SimpleExceptionHandler.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
@Override
public ByteCodeAppender appender(Target implementationTarget) {
    return this;
}
 
Example #29
Source File: TypeInitializer.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public TypeInitializer expandWith(ByteCodeAppender byteCodeAppender) {
    return new TypeInitializer.Simple(new Compound(this.byteCodeAppender, byteCodeAppender));
}
 
Example #30
Source File: AdviceJsrRetTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
public ByteCodeAppender appender(Target implementationTarget) {
    return this;
}