Java Code Examples for net.bytebuddy.dynamic.loading.ClassLoadingStrategy

The following examples show how to use net.bytebuddy.dynamic.loading.ClassLoadingStrategy. 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: promagent   Author: fstab   File: StaticFinalTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
    SortedSet<HookMetadata> hookMetadata = Util.loadHookMetadata(StaticFinalTestHook.class);
    ClassLoaderCache classLoaderCache = Util.mockClassLoaderCache();

    MetricsStore metricsStore = Util.mockMetricsStore();
    Delegator.init(hookMetadata, metricsStore, classLoaderCache);
    MethodCallCounter.reset();

    Map<String, SortedSet<HookMetadata.MethodSignature>> instruments = getInstruments(hookMetadata);
    Set<HookMetadata.MethodSignature> instrumentedMethods = instruments.get(StaticFinalExample.class.getName());
    example = new ByteBuddy()
            .redefine(StaticFinalExample.class)
            .visit(Advice.to(PromagentAdvice.class).on(Promagent.matchAnyMethodIn(instrumentedMethods)))
            .make()
            .load(this.getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .newInstance();
}
 
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 testWithArgument() throws Exception {
    DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy()
            .subclass(MethodCallWithExplicitArgument.class)
            .method(isDeclaredBy(MethodCallWithExplicitArgument.class))
            .intercept(MethodCall.invokeSuper().withArgument(0))
            .make()
            .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class)));
    assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class));
    assertThat(instance.foo(BAR), is(BAR));
}
 
Example #3
Source Project: byte-buddy   Author: raphw   File: SubclassDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPackageDefinition() throws Exception {
    Class<?> packageType = new ByteBuddy()
            .makePackage(FOO)
            .annotateType(AnnotationDescription.Builder.ofType(Foo.class).build())
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(packageType.getSimpleName(), is(PackageDescription.PACKAGE_CLASS_NAME));
    assertThat(packageType.getName(), is(FOO + "." + PackageDescription.PACKAGE_CLASS_NAME));
    assertThat(packageType.getModifiers(), is(PackageDescription.PACKAGE_MODIFIERS));
    assertThat(packageType.getDeclaredFields().length, is(0));
    assertThat(packageType.getDeclaredMethods().length, is(0));
    assertThat(packageType.getDeclaredAnnotations().length, is(1));
    assertThat(packageType.getAnnotation(Foo.class), notNullValue(Foo.class));
}
 
Example #4
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderForInliningTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEnabledAnnotationRetention() throws Exception {
    Class<?> type = create(Annotated.class)
            .field(ElementMatchers.any()).annotateField(new Annotation[0])
            .method(ElementMatchers.any()).intercept(StubMethod.INSTANCE)
            .make()
            .load(new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
                    ClassFileLocator.ForClassLoader.readToNames(SampleAnnotation.class)), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    @SuppressWarnings("unchecked")
    Class<? extends Annotation> sampleAnnotation = (Class<? extends Annotation>) type.getClassLoader().loadClass(SampleAnnotation.class.getName());
    assertThat(type.isAnnotationPresent(sampleAnnotation), is(true));
    assertThat(type.getDeclaredField(FOO).isAnnotationPresent(sampleAnnotation), is(true));
    assertThat(type.getDeclaredMethod(FOO, Void.class).isAnnotationPresent(sampleAnnotation), is(true));
    assertThat(type.getDeclaredMethod(FOO, Void.class).getParameterAnnotations()[0].length, is(1));
    assertThat(type.getDeclaredMethod(FOO, Void.class).getParameterAnnotations()[0][0].annotationType(), is((Object) sampleAnnotation));
}
 
Example #5
Source Project: byte-buddy   Author: raphw   File: EqualsMethodOtherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuperMethod() throws Exception {
    DynamicType.Loaded<?> loaded = new ByteBuddy()
            .subclass(EqualsBase.class)
            .defineField(FOO, Object.class, Visibility.PUBLIC)
            .method(isEquals())
            .intercept(EqualsMethod.requiringSuperClassEquality())
            .make()
            .load(EqualsBase.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
    Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
    left.getClass().getDeclaredField(FOO).set(left, FOO);
    right.getClass().getDeclaredField(FOO).set(right, FOO);
    assertThat(left, is(right));
}
 
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 testMethodReadWithFieldSubstitution() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(MethodInvokeSample.class)
            .visit(MemberSubstitution.strict().method(named(FOO)).replaceWith(MethodInvokeSample.class.getDeclaredField(QUX)).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(QUX).get(instance), is((Object) QUX));
    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) QUX));
    assertThat(type.getDeclaredField(QUX).get(instance), is((Object) QUX));
}
 
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 testInvokeOnMethodCallUsingMatcher() throws Exception {
    DynamicType.Loaded<MethodCallChaining> loaded = new ByteBuddy()
            .subclass(MethodCallChaining.class)
            .method(named("foobar"))
            .intercept(MethodCall.invoke(named("toUpperCase").and(takesArguments(0)))
                    .onMethodCall(MethodCall.invoke(named("bar"))))
            .make()
            .load(MethodCallChaining.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));
    MethodCallChaining instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.foobar(), is("BAR"));
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class)));
    assertThat(instance, instanceOf(MethodCallChaining.class));
}
 
Example #8
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnWildcardWithoutBound() 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();
    Field field = createPlain()
            .defineField(FOO, TypeDescription.Generic.Builder.parameterizedType(TypeDescription.ForLoadedType.of(Collection.class),
                    TypeDescription.Generic.Builder.unboundWildcard(AnnotationDescription.Builder.ofType(typeAnnotationType)
                            .define(VALUE, INTEGER_VALUE).build())).build())
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getDeclaredField(FOO);
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveFieldType(field).ofTypeArgument(0).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveFieldType(field).ofTypeArgument(0).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
}
 
Example #9
Source Project: byte-buddy   Author: raphw   File: TypeResolutionStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public <S extends ClassLoader> Map<TypeDescription, Class<?>> initialize(DynamicType dynamicType,
                                                                         S classLoader,
                                                                         ClassLoadingStrategy<? super S> classLoadingStrategy) {
    Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(dynamicType.getLoadedTypeInitializers());
    TypeDescription instrumentedType = dynamicType.getTypeDescription();
    Map<TypeDescription, Class<?>> types = classLoadingStrategy.load(classLoader, dynamicType.getAllTypes());
    nexusAccessor.register(instrumentedType.getName(),
            types.get(instrumentedType).getClassLoader(),
            identification,
            loadedTypeInitializers.remove(instrumentedType));
    for (Map.Entry<TypeDescription, LoadedTypeInitializer> entry : loadedTypeInitializers.entrySet()) {
        entry.getValue().onLoad(types.get(entry.getKey()));
    }
    return types;
}
 
Example #10
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 testFrameInconsistentParameterTrivialDiscarding() 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(discarding).on(named(FOO)))
            .make();
}
 
Example #11
Source Project: byte-buddy   Author: raphw   File: InvokeDynamicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(7)
public void testBootstrapWithFieldExplicitType() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(Class.forName(BOOTSTRAP_CLASS));
    DynamicType.Loaded<Simple> dynamicType = new ByteBuddy()
            .subclass(Simple.class)
            .defineField(FOO, Object.class)
            .method(isDeclaredBy(Simple.class))
            .intercept(InvokeDynamic.bootstrap(typeDescription.getDeclaredMethods().filter(named("bootstrapSimple")).getOnly())
                    .invoke(QUX, String.class)
                    .withField(FOO).as(String.class)
                    .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredFields().length, is(1));
    Simple instance = dynamicType.getLoaded().getDeclaredConstructor().newInstance();
    Field field = dynamicType.getLoaded().getDeclaredField(FOO);
    field.setAccessible(true);
    field.set(instance, FOO);
    assertThat(instance.foo(), is(FOO));
}
 
Example #12
Source Project: byte-buddy   Author: raphw   File: AdviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAssigningEnterPostProcessorDelegate() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(PostProcessorDelegateTest.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(PostProcessorDelegateTest.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 #13
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnParameterizedType() 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();
    Field field = createPlain()
            .defineField(FOO, TypeDescription.Generic.Builder.parameterizedType(TypeDescription.ForLoadedType.of(Collection.class),
                    TypeDescription.Generic.Builder.unboundWildcard(AnnotationDescription.Builder.ofType(typeAnnotationType)
                            .define(VALUE, INTEGER_VALUE).build()))
                    .build())
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getDeclaredField(FOO);
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveFieldType(field).ofTypeArgument(0).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveFieldType(field).ofTypeArgument(0).asList()
            .ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
}
 
Example #14
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStaticFieldExplicit() throws Exception {
    DynamicType.Loaded<Object> loaded = new ByteBuddy()
            .subclass(Object.class)
            .invokable(isTypeInitializer())
            .intercept(MethodCall.invoke(isEquals())
                    .onField(System.class.getField("out"))
                    .with(""))
            .make()
            .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance, instanceOf(Object.class));
}
 
Example #15
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 testFrameInconsistentThisParameterTrivialDiscarding() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(Object.class)
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new InconsistentThisReferenceMethod())
            .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(discarding).on(named(FOO)))
            .make();
}
 
Example #16
Source Project: byte-buddy   Author: raphw   File: ByteBuddyTutorialExamplesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFieldsAndMethodsForwarding() throws Exception {
    MemoryDatabase memoryDatabase = new MemoryDatabase();
    MemoryDatabase loggingDatabase = new ByteBuddy()
            .subclass(MemoryDatabase.class)
            .method(named("load")).intercept(MethodDelegation
                    .withDefaultConfiguration()
                    .withBinders(Pipe.Binder.install(Forwarder.class))
                    .to(new ForwardingLoggerInterceptor(memoryDatabase)))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance();
    assertThat(loggingDatabase.load("qux"), is(Arrays.asList("qux: foo", "qux: bar")));
}
 
Example #17
Source Project: byte-buddy   Author: raphw   File: ByteBuddyTutorialExamplesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFieldsAndMethodsFieldAccess() throws Exception {
    ByteBuddy byteBuddy = new ByteBuddy();
    Class<? extends UserType> dynamicUserType = byteBuddy
            .subclass(UserType.class)
            .defineField("interceptor", Interceptor2.class, Visibility.PRIVATE)
            .method(not(isDeclaredBy(Object.class))).intercept(MethodDelegation.toField("interceptor"))
            .implement(InterceptionAccessor.class).intercept(FieldAccessor.ofBeanProperty())
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    InstanceCreator factory = byteBuddy
            .subclass(InstanceCreator.class)
            .method(not(isDeclaredBy(Object.class))).intercept(MethodDelegation.toConstructor(dynamicUserType))
            .make()
            .load(dynamicUserType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance();
    UserType userType = (UserType) factory.makeInstance();
    ((InterceptionAccessor) userType).setInterceptor(new HelloWorldInterceptor());
    assertThat(userType.doSomething(), is("Hello World!"));
}
 
Example #18
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testTypeAnnotationOnInterfaceType() 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()
            .merge(TypeManifestation.ABSTRACT)
            .implement(TypeDescription.Generic.Builder.rawType(Runnable.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE).build()))
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(type.getInterfaces().length, is(1));
    assertThat(type.getInterfaces()[0], is((Object) Runnable.class));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveInterfaceType(type, 0).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveInterfaceType(type, 0).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
}
 
Example #19
Source Project: byte-buddy   Author: raphw   File: AdviceInconsistentFrameTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
@JavaVersionRule.Enforce(7)
public void testFrameInconsistentThisParameter() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(Object.class)
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new InconsistentThisReferenceMethod())
            .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(retaining).on(named(FOO)))
            .make();
}
 
Example #20
Source Project: byte-buddy   Author: raphw   File: ToStringMethodOtherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIgnoredField() throws Exception {
    DynamicType.Loaded<?> loaded = new ByteBuddy()
            .subclass(Object.class)
            .defineField(FOO, Object.class, Visibility.PUBLIC)
            .method(isToString())
            .intercept(ToStringMethod.prefixedBy(FOO).withIgnoredFields(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
    Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    instance.getClass().getDeclaredField(FOO).set(instance, FOO);
    assertThat(instance.toString(), is("foo{}"));
}
 
Example #21
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 testFrameInconsistentThisParameterTrivialCopying() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(Object.class)
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new InconsistentThisReferenceMethod())
            .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 #22
Source Project: byte-buddy   Author: raphw   File: JavaConstantDynamicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(11)
public void testDynamicConstantConstructorLookupOnly() throws Exception {
    Class<?> bootstrap = Class.forName("net.bytebuddy.test.precompiled.DynamicConstantBootstrap");
    Class<? extends Foo> baz = new ByteBuddy()
            .subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(FixedValue.value(JavaConstant.Dynamic.bootstrap(FOO, bootstrap.getConstructor(
                    Class.forName("java.lang.invoke.MethodHandles$Lookup"),
                    Object[].class))))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(baz.getDeclaredFields().length, is(0));
    assertThat(baz.getDeclaredMethods().length, is(1));
    Foo foo = baz.getDeclaredConstructor().newInstance();
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), instanceOf(bootstrap));
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));
}
 
Example #23
Source Project: byte-buddy   Author: raphw   File: EqualsMethodOtherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIgnoredField() throws Exception {
    DynamicType.Loaded<?> loaded = new ByteBuddy()
            .subclass(Object.class)
            .defineField(FOO, Object.class, Visibility.PUBLIC)
            .method(isEquals())
            .intercept(EqualsMethod.isolated().withIgnoredFields(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
    Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
    left.getClass().getDeclaredField(FOO).set(left, FOO);
    left.getClass().getDeclaredField(FOO).set(left, BAR);
    assertThat(left, is(right));
}
 
Example #24
Source Project: byte-buddy   Author: raphw   File: JavaConstantDynamicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(11)
public void testDynamicConstantConstructorVarargs() throws Exception {
    Class<?> bootstrap = Class.forName("net.bytebuddy.test.precompiled.DynamicConstantBootstrap");
    Class<? extends Foo> baz = new ByteBuddy()
            .subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(FixedValue.value(JavaConstant.Dynamic.bootstrap(FOO, bootstrap.getConstructor(
                    Class.forName("java.lang.invoke.MethodHandles$Lookup"),
                    String.class,
                    Class.class,
                    Object[].class))))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(baz.getDeclaredFields().length, is(0));
    assertThat(baz.getDeclaredMethods().length, is(1));
    Foo foo = baz.getDeclaredConstructor().newInstance();
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), instanceOf(bootstrap));
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));
}
 
Example #25
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 testReceiverTypeInterception() 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()
            .method(named("toString"))
            .intercept(StubMethod.INSTANCE)
            .receiverType(TypeDescription.Generic.Builder.rawType(TargetType.class)
                    .annotate(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, BAZ).build())
                    .build())
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredMethod("toString");
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveReceiverType(method).getDeclaredAnnotations().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveReceiverType(method).getDeclaredAnnotations()
            .ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(BAZ));
}
 
Example #26
Source Project: byte-buddy   Author: raphw   File: MethodDelegationConstructionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testConstruction() throws Exception {
    DynamicType.Loaded<T> loaded = new ByteBuddy()
            .subclass(sourceType)
            .method(isDeclaredBy(sourceType))
            .intercept(MethodDelegation.toConstructor(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));
    Object value = loaded.getLoaded().getDeclaredMethod(FOO, parameterTypes).invoke(instance, arguments);
    assertThat(value, instanceOf(targetType));
    Field field = targetType.getDeclaredField("value");
    field.setAccessible(true);
    assertThat(field.get(value), (Matcher) matcher);
    instance.assertZeroCalls();
}
 
Example #27
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWithExplicitArgumentField() throws Exception {
    DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy()
            .subclass(MethodCallWithExplicitArgument.class)
            .method(isDeclaredBy(MethodCallWithExplicitArgument.class))
            .intercept(MethodCall.invokeSuper().withReference(FOO))
            .make()
            .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
    MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class)));
    assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class));
    assertThat(instance.foo(BAR), is(FOO));
}
 
Example #28
Source Project: byte-buddy   Author: raphw   File: JavaConstantDynamicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(11)
public void testInvoke() throws Exception {
    Class<? extends Foo> baz = new ByteBuddy()
            .subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(FixedValue.value(JavaConstant.Dynamic.ofInvocation(SampleClass.class.getMethod("make"))))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(baz.getDeclaredFields().length, is(0));
    assertThat(baz.getDeclaredMethods().length, is(1));
    Foo foo = baz.getDeclaredConstructor().newInstance();
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), instanceOf(SampleClass.class));
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));
}
 
Example #29
Source Project: byte-buddy   Author: raphw   File: JavaConstantDynamicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(11)
public void testConstruct() throws Exception {
    Class<? extends Foo> baz = new ByteBuddy()
            .subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(FixedValue.value(JavaConstant.Dynamic.ofInvocation(SampleClass.class.getConstructor())))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(baz.getDeclaredFields().length, is(0));
    assertThat(baz.getDeclaredMethods().length, is(1));
    Foo foo = baz.getDeclaredConstructor().newInstance();
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), instanceOf(SampleClass.class));
    assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));
}
 
Example #30
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnGenericComponentType() 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();
    Field field = createPlain()
            .defineField(FOO, TypeDescription.Generic.Builder.parameterizedType(TypeDescription.ForLoadedType.of(Collection.class),
                    TypeDescription.Generic.Builder.unboundWildcard())
                    .annotate(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE).build())
                    .asArray()
                    .build())
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getDeclaredField(FOO);
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveFieldType(field).ofComponentType().asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveFieldType(field).ofComponentType().asList()
            .ofType(typeAnnotationType).getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
}