Java Code Examples for net.bytebuddy.ByteBuddy

The following examples show how to use net.bytebuddy.ByteBuddy. These examples are extracted from open source projects. 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 Project: byte-buddy   Author: raphw   File: AdviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAdviceNotSkipExceptionImplicit() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(Sample.class)
            .visit(Advice.to(TrivialAdvice.class).on(named(FOO + BAR)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    try {
        type.getDeclaredMethod(FOO + BAR).invoke(type.getDeclaredConstructor().newInstance());
        fail();
    } catch (InvocationTargetException exception) {
        assertThat(exception.getCause(), instanceOf(RuntimeException.class));
    }
    assertThat(type.getDeclaredField(ENTER).get(null), is((Object) 1));
    assertThat(type.getDeclaredField(EXIT).get(null), is((Object) 1));
}
 
Example #2
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOnFieldUsingMatcher() throws Exception {
    DynamicType.Loaded<MethodCallOnField> loaded = new ByteBuddy()
            .subclass(MethodCallOnField.class)
            .method(named("foo"))
            .intercept(MethodCall.invoke(named("trim")).onField("foo"))
            .make()
            .load(MethodCallOnField.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallOnField instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    instance.foo = " abc ";
    assertThat(instance, instanceOf(MethodCallOnField.class));
    assertThat(instance.foo(), is("abc"));
}
 
Example #3
Source Project: byte-buddy   Author: raphw   File: SubclassDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnSuperClass() 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 = new ByteBuddy()
            .subclass(TypeDescription.Generic.Builder.rawType(Object.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, BAZ).build()))
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(type.getSuperclass(), is((Object) Object.class));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveSuperClassType(type).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveSuperClassType(type).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(BAZ));
}
 
Example #4
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectConstruction() throws Exception {
    DynamicType.Loaded<SelfReference> loaded = new ByteBuddy()
            .subclass(SelfReference.class)
            .method(isDeclaredBy(SelfReference.class))
            .intercept(MethodCall.construct(SelfReference.class.getDeclaredConstructor()))
            .make()
            .load(SelfReference.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    SelfReference instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    SelfReference created = instance.foo();
    assertThat(created.getClass(), CoreMatchers.<Class<?>>is(SelfReference.class));
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SelfReference.class)));
    assertThat(instance, instanceOf(SelfReference.class));
    assertThat(created, not(instance));
}
 
Example #5
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(value = 7, atMost = 7, j9 = false)
public void testJava7TypesExplicit() throws Exception {
    DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy()
            .subclass(SimpleMethod.class)
            .method(named(FOO))
            .intercept(MethodCall.invoke(Foo.class.getDeclaredMethod(BAR, Object.class, Object.class))
                    .with(JavaConstant.MethodHandle.ofLoaded(makeMethodHandle()), JavaConstant.MethodType.ofLoaded(makeMethodType(void.class))))
            .make()
            .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.foo(), is("" + makeMethodHandle() + makeMethodType(void.class)));
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class)));
    assertThat(instance, instanceOf(SimpleMethod.class));
}
 
Example #6
Source Project: byte-buddy   Author: raphw   File: MemberSubstitutionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStaticFieldReadWithMethodSubstitution() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(StaticFieldAccessSample.class)
            .visit(MemberSubstitution.strict().field(named(FOO)).replaceWith(StaticFieldAccessSample.class.getDeclaredMethod(BAZ)).on(named(RUN)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Object instance = type.getDeclaredConstructor().newInstance();
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
    assertThat(type.getDeclaredField(BAR).get(null), is((Object) BAR));
    assertThat(type.getDeclaredField(BAZ).get(null), is((Object) BAZ));
    assertThat(type.getDeclaredMethod(RUN).invoke(instance), nullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
    assertThat(type.getDeclaredField(BAR).get(null), is((Object) BAZ));
    assertThat(type.getDeclaredField(BAZ).get(null), is((Object) BAZ));
}
 
Example #7
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeOnArgumentUsingMatcher() throws Exception {
    DynamicType.Loaded<ArgumentCall> loaded = new ByteBuddy()
            .subclass(ArgumentCall.class)
            .method(named("foo"))
            .intercept(MethodCall.invoke(named("toUpperCase").and(takesArguments(0))).onMethodCall(MethodCall.invoke(named("foo")).onArgument(0)))
            .make()
            .load(ArgumentCall.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    ArgumentCall instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.foo(new ArgumentCall.Target("foo")), is("FOO"));
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class)));
    assertThat(instance, instanceOf(ArgumentCall.class));
}
 
Example #8
Source Project: unsafe   Author: bramp   File: UnrolledUnsafeCopierBuilder.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructs a new Copier using the passed in Unsafe instance
 *
 * @param unsafe The sun.misc.Unsafe instance this copier uses
 * @return The new UnsageCopier built with the specific parameters
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException  if any argument is invalid
 */
public UnsafeCopier build(Unsafe unsafe)
    throws IllegalAccessException, InstantiationException, NoSuchMethodException,
    InvocationTargetException {

  checkArgument(offset >= 0, "Offset must be set");
  checkArgument(length >= 0, "Length must be set");
  checkNotNull(unsafe);

  Class<?> dynamicType = new ByteBuddy()
      .subclass(UnsafeCopier.class)
      .method(named("copy"))
      .intercept(new CopierImplementation(offset, length)).make()
      .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
      .getLoaded();

  return (UnsafeCopier) dynamicType.getDeclaredConstructor(Unsafe.class).newInstance(unsafe);
}
 
Example #9
Source Project: byte-buddy   Author: raphw   File: AdviceInconsistentFrameTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(7)
public void testFrameInconsistentParameterTrivialCopying() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(Object.class)
            .defineMethod(FOO, String.class, Visibility.PUBLIC, Ownership.STATIC)
            .withParameters(Void.class)
            .intercept(new InconsistentParameterReferenceMethod())
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER_PERSISTENT)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO, Void.class).invoke(null, (Object) null), is((Object) BAR));
    new ByteBuddy()
            .redefine(type)
            .visit(Advice.to(copying).on(named(FOO)))
            .make();
}
 
Example #10
Source Project: byte-buddy   Author: raphw   File: FixedValueConstantPoolTypesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConstantPool() throws Exception {
    DynamicType.Loaded<T> loaded = new ByteBuddy()
            .subclass(helperClass)
            .method(isDeclaredBy(helperClass))
            .intercept(FixedValue.value(fixedValue))
            .make()
            .load(helperClass.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(2));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    T instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(StringTarget.class)));
    assertThat(instance, instanceOf(helperClass));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO).invoke(instance), is(fixedValue));
    assertThat(loaded.getLoaded().getDeclaredMethod(BAR).invoke(instance), is(fixedValue));
    instance.assertZeroCalls();
}
 
Example #11
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSelfInvocation() throws Exception {
    SuperMethodInvocation delegate = mock(SuperMethodInvocation.class);
    when(delegate.foo()).thenReturn(FOO);
    DynamicType.Loaded<SuperMethodInvocation> loaded = new ByteBuddy()
            .subclass(SuperMethodInvocation.class)
            .method(takesArguments(0).and(named(FOO)))
            .intercept(MethodCall.invokeSelf().on(delegate))
            .make()
            .load(SuperMethodInvocation.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
    SuperMethodInvocation instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SuperMethodInvocation.class)));
    assertThat(instance, instanceOf(SuperMethodInvocation.class));
    assertThat(instance.foo(), is(FOO));
    verify(delegate).foo();
    verifyNoMoreInteractions(delegate);
}
 
Example #12
Source Project: byte-buddy   Author: raphw   File: AdviceInconsistentFrameTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(7)
public void testFrameDropImplicitTrivialCopying() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(Object.class)
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new DropImplicitMethod())
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER_PERSISTENT)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) BAR));
    new ByteBuddy()
            .redefine(type)
            .visit(Advice.to(copying).on(named(FOO)))
            .make();
}
 
Example #13
Source Project: byte-buddy   Author: raphw   File: AdviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionNotCatchedAdvice() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(ExceptionNotCatchedAdvice.class)
            .visit(Advice.to(ExceptionNotCatchedAdvice.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    try {
        type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance());
        fail();
    } catch (InvocationTargetException exception) {
        assertThat(exception.getCause(), instanceOf(Exception.class));
    }
    assertThat(type.getDeclaredField(ENTER).get(null), is((Object) 1));
    assertThat(type.getDeclaredField(EXIT).get(null), is((Object) 0));
}
 
Example #14
Source Project: byte-buddy   Author: raphw   File: MethodCallProxy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType make(String auxiliaryTypeName,
                        ClassFileVersion classFileVersion,
                        MethodAccessorFactory methodAccessorFactory) {
    MethodDescription accessorMethod = methodAccessorFactory.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    LinkedHashMap<String, TypeDescription> parameterFields = extractFields(accessorMethod);
    DynamicType.Builder<?> builder = new ByteBuddy(classFileVersion)
            .with(TypeValidation.DISABLED)
            .with(PrecomputedMethodGraph.INSTANCE)
            .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .name(auxiliaryTypeName)
            .modifiers(DEFAULT_TYPE_MODIFIER)
            .implement(Runnable.class, Callable.class).intercept(new MethodCall(accessorMethod, assigner))
            .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0])
            .defineConstructor().withParameters(parameterFields.values())
            .intercept(ConstructorCall.INSTANCE);
    for (Map.Entry<String, TypeDescription> field : parameterFields.entrySet()) {
        builder = builder.defineField(field.getKey(), field.getValue(), Visibility.PRIVATE);
    }
    return builder.make();
}
 
Example #15
Source Project: byte-buddy   Author: raphw   File: MemberSubstitutionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodReadWithMethodSubstitution() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(MethodInvokeSample.class)
            .visit(MemberSubstitution.strict().method(named(FOO)).replaceWith(MethodInvokeSample.class.getDeclaredMethod(BAZ)).on(named(RUN)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Object instance = type.getDeclaredConstructor().newInstance();
    assertThat(type.getDeclaredField(FOO).get(instance), is((Object) FOO));
    assertThat(type.getDeclaredField(BAR).get(instance), is((Object) BAR));
    assertThat(type.getDeclaredField(BAZ).get(instance), is((Object) BAZ));
    assertThat(type.getDeclaredMethod(RUN).invoke(instance), nullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(instance), is((Object) FOO));
    assertThat(type.getDeclaredField(BAR).get(instance), is((Object) BAZ));
    assertThat(type.getDeclaredField(BAZ).get(instance), is((Object) BAZ));
}
 
Example #16
Source Project: byte-buddy   Author: raphw   File: MethodDelegationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testStaticMethodBinding() throws Exception {
    DynamicType.Loaded<T> loaded = new ByteBuddy()
            .subclass(sourceType)
            .method(isDeclaredBy(sourceType))
            .intercept(MethodDelegation.to(targetType))
            .make()
            .load(sourceType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    T instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(sourceType)));
    assertThat(instance, instanceOf(sourceType));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO, parameterTypes).invoke(instance, arguments), (Matcher) matcher);
    instance.assertZeroCalls();
}
 
Example #17
Source Project: byte-buddy   Author: raphw   File: ByteArrayClassLoaderChildFirstTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    classLoader = new ByteArrayClassLoader.ChildFirst(getClass().getClassLoader(),
            Collections.singletonMap(Foo.class.getName(), new ByteBuddy()
                    .redefine(Bar.class)
                    .visit(new RenamingWrapper(Bar.class.getName().replace('.', '/'), Foo.class.getName().replace('.', '/')))
                    .make()
                    .getBytes()),
            DEFAULT_PROTECTION_DOMAIN,
            persistenceHandler,
            PackageDefinitionStrategy.NoOp.INSTANCE);
}
 
Example #18
Source Project: byte-buddy   Author: raphw   File: MethodDelegationSuperMethodTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
@JavaVersionRule.Enforce(8)
public void testDefaultMethodFallbackAmbiguous() throws Exception {
    new ByteBuddy()
            .subclass(Object.class)
            .implement(Class.forName(SINGLE_DEFAULT_METHOD), Class.forName(CONFLICTING_INTERFACE))
            .intercept(MethodDelegation.to(NonVoidTarget.class))
            .make();
}
 
Example #19
Source Project: byte-buddy   Author: raphw   File: GenericSignatureResolutionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeVariableClassAndInterfaceBound() throws Exception {
    DynamicType.Unloaded<?> unloaded = new ByteBuddy()
            .redefine(TypeVariableClassAndInterfaceBound.class)
            .make();
    Class<?> type = unloaded.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    TypeDescription createdType = TypeDescription.ForLoadedType.of(type);
    TypeDescription originalType = TypeDescription.ForLoadedType.of(TypeVariableClassAndInterfaceBound.class);
    assertThat(createdType.getTypeVariables(), is(originalType.getTypeVariables()));
    assertThat(createdType.getSuperClass(), is(originalType.getSuperClass()));
    assertThat(createdType.getInterfaces(), is(originalType.getInterfaces()));
}
 
Example #20
Source Project: byte-buddy   Author: raphw   File: TypeWriterDeclarationPreservationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDecoration() throws Exception {
    TypeModifierExtractor typeModifierExtractor = new TypeModifierExtractor();
    OpenedClassReader.of(ClassFileLocator.ForClassLoader.read(type)).accept(typeModifierExtractor, 0);
    new ByteBuddy()
            .decorate(type)
            .visit(new TypeValidator.Wrapper(typeModifierExtractor))
            .make();
}
 
Example #21
Source Project: byte-buddy   Author: raphw   File: EqualsMethodOtherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInstanceOf() throws Exception {
    DynamicType.Loaded<?> superClass = new ByteBuddy()
            .subclass(Object.class)
            .method(isEquals())
            .intercept(EqualsMethod.isolated().withSubclassEquality())
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
    DynamicType.Loaded<?> subClass = new ByteBuddy()
            .subclass(superClass.getLoaded())
            .make()
            .load(superClass.getLoaded().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(superClass.getLoaded().getDeclaredConstructor().newInstance(), is(subClass.getLoaded().getDeclaredConstructor().newInstance()));
    assertThat(subClass.getLoaded().getDeclaredConstructor().newInstance(), is(superClass.getLoaded().getDeclaredConstructor().newInstance()));
}
 
Example #22
Source Project: byte-buddy   Author: raphw   File: TypeWriterDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
public void testTypeInitializerOnRebasedModernInterface() throws Exception {
    assertThat(new ByteBuddy()
            .rebase(Class.forName(JAVA_8_INTERFACE))
            .invokable(isTypeInitializer())
            .intercept(StubMethod.INSTANCE)
            .make(), notNullValue(DynamicType.class));
}
 
Example #23
Source Project: byte-buddy   Author: raphw   File: AdviceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyAdviceEntryAndExitWithExceptionHandlingAndSuppression() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(EmptyMethod.class)
            .visit(Advice.to(EmptyAdviceWithExceptionHandlingAndSuppression.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), nullValue(Object.class));
}
 
Example #24
Source Project: byte-buddy   Author: raphw   File: AdviceSkipOnTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInstanceOfNoSkip() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(InstanceOfNoSkip.class)
            .visit(Advice.to(InstanceOfNoSkip.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #25
Source Project: byte-buddy   Author: raphw   File: AdviceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testOriginMethodNonAssignableAdvice() throws Exception {
    new ByteBuddy()
            .redefine(Sample.class)
            .visit(Advice.to(OriginMethodAdvice.class).on(isConstructor()))
            .make();
}
 
Example #26
Source Project: byte-buddy   Author: raphw   File: FieldAccessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInstanceDefault() throws Exception {
    DynamicType.Loaded<?> loaded = new ByteBuddy()
            .subclass(instanceSwap)
            .method(isDeclaredBy(instanceSwap))
            .intercept(FieldAccessor.ofField(FOO).setsDefaultValue())
            .make()
            .load(instanceSwap.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(loaded.getLoaded().getMethod(FOO).invoke(instance), nullValue(Object.class));
    assertThat(loaded.getLoaded().getField(FOO).get(instance), not(value));
}
 
Example #27
Source Project: byte-buddy   Author: raphw   File: InvokeDynamicTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = LinkageError.class)
@JavaVersionRule.Enforce(8)
public void testLambdaMetaFactoryIllegalBinding() throws Exception {
    DynamicType.Loaded<FunctionalFactory> dynamicType = new ByteBuddy()
            .subclass(FunctionalFactory.class)
            .method(isDeclaredBy(FunctionalFactory.class))
            .intercept(InvokeDynamic.lambda(InvokeDynamicTest.class.getMethod("value"), Callable.class).withValue(FOO))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredFields().length, is(0));
    assertThat(dynamicType.getLoaded().getDeclaredConstructor().newInstance().make().call(), is(FOO));
}
 
Example #28
Source Project: byte-buddy   Author: raphw   File: AdviceExitValueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEnterValueSubstitution() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(Sample.class)
            .visit(Advice.to(ExitSubstitutionAdvice.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #29
Source Project: byte-buddy   Author: raphw   File: AdviceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testAdviceWithNonAssignableThisReference() throws Exception {
    new ByteBuddy()
            .redefine(Sample.class)
            .visit(Advice.to(IllegalThisReferenceAdvice.class).on(named(FOO)))
            .make();
}
 
Example #30
Source Project: byte-buddy   Author: raphw   File: MethodDelegationFieldProxyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExplicitFieldAccessExplicitTarget() throws Exception {
    DynamicType.Loaded<ExplicitInherited> loaded = new ByteBuddy()
            .subclass(ExplicitInherited.class)
            .method(isDeclaredBy(ExplicitInherited.class))
            .intercept(MethodDelegation.withDefaultConfiguration().withBinders(FieldProxy.Binder.install(Get.class, Set.class)).to(SwapInherited.class))
            .make()
            .load(ExplicitInherited.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    ExplicitInherited explicitInherited = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(((Explicit) explicitInherited).foo, is(FOO));
    assertThat(explicitInherited.foo, is(QUX));
    explicitInherited.swap();
    assertThat(((Explicit) explicitInherited).foo, is(FOO + BAR));
    assertThat(explicitInherited.foo, is(QUX));
}