net.bytebuddy.implementation.MethodDelegation Java Examples

The following examples show how to use net.bytebuddy.implementation.MethodDelegation. 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: alibaba-rsocket-broker   Author: alibaba   File: RSocketRemoteServiceBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T build() {
    CONSUMED_SERVICES.add(new ServiceLocator(group, service, version));
    RSocketRequesterRpcProxy proxy = getRequesterProxy();
    Class<T> dynamicType = (Class<T>) new ByteBuddy(ClassFileVersion.JAVA_V8)
            .subclass(serviceInterface)
            .name(serviceInterface.getSimpleName() + "RSocketStub")
            .method(ElementMatchers.not(ElementMatchers.isDefaultMethod()))
            .intercept(MethodDelegation.to(proxy))
            .make()
            .load(serviceInterface.getClassLoader())
            .getLoaded();
    try {
        return dynamicType.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source Project: sofa-rpc   Author: sofastack   File: BytebuddyProxy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) {

    Class<? extends T> cls = PROXY_CLASS_MAP.get(interfaceClass);
    if (cls == null) {
        cls = new ByteBuddy()
            .subclass(interfaceClass)
            .method(
                ElementMatchers.isDeclaredBy(interfaceClass).or(ElementMatchers.isEquals())
                    .or(ElementMatchers.isToString().or(ElementMatchers.isHashCode())))
            .intercept(MethodDelegation.to(new BytebuddyInvocationHandler(proxyInvoker), "handler"))
            .make()
            .load(interfaceClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded();

        PROXY_CLASS_MAP.put(interfaceClass, cls);
    }
    try {
        return cls.newInstance();
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSTRUCT, "bytebuddy"), t);
    }

}
 
Example #3
Source Project: reflection-util   Author: cronn-de   File: MethodCaptor.java    License: Apache License 2.0 6 votes vote down vote up
static <T> Class<? extends T> createProxyClass(Class<T> beanClass) {
	try {
		return new ByteBuddy()
			.subclass(beanClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
			.defineField(MethodCaptor.FIELD_NAME, MethodCaptor.class, Visibility.PRIVATE)
			.method(isMethod()
				.and(takesArguments(0))
				.and(not(isDeclaredBy(Object.class))))
			.intercept(MethodDelegation.to(MethodCaptor.class))
			.make()
			.load(PropertyUtils.class.getClassLoader())
			.getLoaded();
	} catch (IllegalAccessError e) {
		throw new ReflectionRuntimeException("Failed to create proxy on " + beanClass, e);
	}
}
 
Example #4
Source Project: JGiven   Author: TNG   File: ByteBuddyStageClassCreator.java    License: Apache License 2.0 6 votes vote down vote up
public <T> Class<? extends T> createStageClass( Class<T> stageClass ) {
    return new ByteBuddy()
        .subclass( stageClass, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING )
        .implement( StageInterceptorInternal.class )
        .defineField( INTERCEPTOR_FIELD_NAME, StepInterceptor.class )
        .method( named(SETTER_NAME) )
            .intercept(
                MethodDelegation.withDefaultConfiguration()
                    .withBinders( FieldProxy.Binder.install(
                            StepInterceptorGetterSetter.class ))
            .to(new StepInterceptorSetter() ))
        .method( not( named( SETTER_NAME )
                .or(ElementMatchers.isDeclaredBy(Object.class))))
        .intercept(
                MethodDelegation.withDefaultConfiguration()
                .withBinders(FieldProxy.Binder.install(
                        StepInterceptorGetterSetter.class ))
            .to( new ByteBuddyMethodInterceptor() ))
        .make()
        .load( getClassLoader(stageClass),
            getClassLoadingStrategy( stageClass ) )
        .getLoaded();
}
 
Example #5
@Test
@JavaVersionRule.Enforce(7)
public void testMethodHandleLoaded() throws Exception {
    Method publicLookup = Class.forName("java.lang.invoke.MethodHandles").getDeclaredMethod("publicLookup");
    Object lookup = publicLookup.invoke(null);
    Method unreflected = Class.forName("java.lang.invoke.MethodHandles$Lookup").getDeclaredMethod("unreflect", Method.class);
    Object methodHandleLoaded = unreflected.invoke(lookup, Foo.class.getDeclaredMethod(FOO));
    assertThat(JavaConstant.MethodHandle.ofLoaded(new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, methodHandleLoaded))
                    .to(Foo.class))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .foo()), is(JavaConstant.MethodHandle.ofLoaded(methodHandleLoaded)));
}
 
Example #6
@Test
@JavaVersionRule.Enforce(7)
public void testMethodHandle() throws Exception {
    Method publicLookup = Class.forName("java.lang.invoke.MethodHandles").getDeclaredMethod("publicLookup");
    Object lookup = publicLookup.invoke(null);
    Method unreflected = Class.forName("java.lang.invoke.MethodHandles$Lookup").getDeclaredMethod("unreflect", Method.class);
    Object methodHandleLoaded = unreflected.invoke(lookup, Foo.class.getDeclaredMethod(FOO));
    assertThat(JavaConstant.MethodHandle.ofLoaded(new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, JavaConstant.MethodHandle.ofLoaded(methodHandleLoaded)))
                    .to(Foo.class))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .foo()), is(JavaConstant.MethodHandle.ofLoaded(methodHandleLoaded)));
}
 
Example #7
@Test
@JavaVersionRule.Enforce(7)
public void testMethodTypeLoaded() throws Exception {
    Object loadedMethodType = JavaType.METHOD_TYPE.load().getDeclaredMethod("methodType", Class.class, Class[].class)
            .invoke(null, void.class, new Class<?>[]{Object.class});
    assertThat(JavaConstant.MethodType.ofLoaded(new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, loadedMethodType))
                    .to(Foo.class))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .foo()), is(JavaConstant.MethodType.ofLoaded(loadedMethodType)));
}
 
Example #8
@Test
@JavaVersionRule.Enforce(7)
public void testMethodType() throws Exception {
    Object loadedMethodType = JavaType.METHOD_TYPE.load().getDeclaredMethod("methodType", Class.class, Class[].class)
            .invoke(null, void.class, new Class<?>[]{Object.class});
    assertThat(JavaConstant.MethodType.ofLoaded(new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, JavaConstant.MethodType.ofLoaded(loadedMethodType)))
                    .to(Foo.class))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .foo()), is(JavaConstant.MethodType.ofLoaded(loadedMethodType)));
}
 
Example #9
Source Project: byte-buddy   Author: raphw   File: RebaseDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
public void testDefaultInterfaceSubInterface() throws Exception {
    Class<?> interfaceType = Class.forName(DEFAULT_METHOD_INTERFACE);
    Class<?> dynamicInterfaceType = new ByteBuddy()
            .rebase(interfaceType)
            .method(named(FOO)).intercept(MethodDelegation.to(InterfaceOverrideInterceptor.class))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    Class<?> dynamicClassType = new ByteBuddy()
            .subclass(dynamicInterfaceType)
            .make()
            .load(dynamicInterfaceType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(dynamicClassType.getMethod(FOO).invoke(dynamicClassType.getDeclaredConstructor().newInstance()), is((Object) (FOO + BAR)));
    assertThat(dynamicInterfaceType.getDeclaredMethods().length, is(3));
    assertThat(dynamicClassType.getDeclaredMethods().length, is(0));
}
 
Example #10
Source Project: tutorials   Author: eugenp   File: ByteBuddyUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
    Class<?> type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();

    Method m = type.getDeclaredMethod("custom", null);

    assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
    assertNotNull(type.getDeclaredField("x"));

}
 
Example #11
Source Project: alibaba-rsocket-broker   Author: alibaba   File: ByteBuddyProxyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGrpcProxy() throws Exception {
    DemoInterceptor interceptor = new DemoInterceptor();
    Class<ReactorAccountServiceGrpc.AccountServiceImplBase> dynamicType = (Class<ReactorAccountServiceGrpc.AccountServiceImplBase>) new ByteBuddy()
            .subclass(ReactorAccountServiceGrpc.AccountServiceImplBase.class)
            .method(ElementMatchers.returns(target -> target.isAssignableFrom(Mono.class) || target.isAssignableFrom(Flux.class)))
            .intercept(MethodDelegation.to(interceptor))
            .make()
            .load(getClass().getClassLoader())
            .getLoaded();
    System.out.println(dynamicType.newInstance().findById(Mono.just(Int32Value.newBuilder().setValue(1).build())).block());
}
 
Example #12
Source Project: arvo2parquet   Author: tideworks   File: ValidateAvroSchema.java    License: MIT License 5 votes vote down vote up
public static void bytecodePatchAvroSchemaClass(final File avroSchemaClassesDir) throws ClassNotFoundException, IOException {
  final String avroSchemaClassPackageName = "org.apache.avro";
  final String avroSchemaFullClassName = avroSchemaClassPackageName + ".Schema";
  final String relativeFilePath = getClassRelativeFilePath(avroSchemaClassPackageName, avroSchemaFullClassName);
  final File clsFile = new File(avroSchemaClassesDir, relativeFilePath);
  Files.deleteIfExists(clsFile.toPath());
  final Class<?>[] methArgTypesMatch = { String.class };
  final DynamicType.Unloaded<?> avroSchemaClsUnloaded = new ByteBuddy()
          .rebase(Class.forName(avroSchemaFullClassName))
          .method(named("validateName").and(returns(String.class)).and(takesArguments(methArgTypesMatch))
                  .and(isPrivate()).and(isStatic()))
          .intercept(MethodDelegation.to(AvroSchemaInterceptor.class))
          .make();
  avroSchemaClsUnloaded.saveIn(avroSchemaClassesDir);
}
 
Example #13
Source Project: Selenium-Foundation   Author: Nordstrom   File: RevisedCapabilityMatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Dynamically generate a replacement for the {@code SafariSpecificValidator} class.
 * 
 * @param validatorClass {@code SafariSpecificValidator} class
 * @return dynamically-generated {@code RevisedSafariValidator} class
 */
private static Class<?> subclassSafariValidator(Class<?> validatorClass) {
    Class<?> validatorIntfc = validatorClass.getInterfaces()[0];
    return new ByteBuddy()
        .subclass(validatorIntfc)
        .name(REVISED_SAFARI_VALIDATOR)
        .method(named("apply"))
        .intercept(MethodDelegation.to(SafariValidator.class))
        .make()
        .load(validatorClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
        .getLoaded();
}
 
Example #14
Source Project: yanwte2   Author: winteryoung   File: ServiceOrchestratorLoader.java    License: Apache License 2.0 5 votes vote down vote up
private static <T extends Function<?, ?>> ServiceTypeIndexEntry createServiceTypeIndexEntry(
        Class<T> serviceType) {
    ServiceOrchestrator<?> userDefinedOrchestrator = loadUserDefinedOrchestrator(serviceType);
    checkState(
            userDefinedOrchestrator != null,
            "Cannot find orchestrator for service: " + serviceType.getName());

    Lazy<Combinator> lazyTree = CombinatorTreeCache.getLazyTree(userDefinedOrchestrator);

    Class<? extends T> proxyType =
            new ByteBuddy()
                    .subclass(serviceType)
                    .method(ElementMatchers.named("apply"))
                    .intercept(
                            MethodDelegation.to(
                                    createInterceptor(lazyTree, userDefinedOrchestrator)))
                    .make()
                    .load(serviceType.getClassLoader())
                    .getLoaded();

    try {
        T proxy = proxyType.newInstance();

        ServiceTypeIndexEntry entry = new ServiceTypeIndexEntry();
        entry.proxy = proxy;
        entry.orchestrator = userDefinedOrchestrator;

        return entry;
    } catch (Exception e) {
        Throwables.throwIfUnchecked(e);
        throw new RuntimeException(e);
    }
}
 
Example #15
Source Project: lams   Author: lamsfoundation   File: ByteBuddyState.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ProxyDefinitionHelpers() {
	this.groovyGetMetaClassFilter = isSynthetic().and( named( "getMetaClass" )
			.and( returns( td -> "groovy.lang.MetaClass".equals( td.getName() ) ) ) );
	this.virtualNotFinalizerFilter = isVirtual().and( not( isFinalizer() ) );
	this.hibernateGeneratedMethodFilter = nameStartsWith( "$$_hibernate_" ).and( isVirtual() );

	PrivilegedAction<MethodDelegation> delegateToInterceptorDispatcherMethodDelegationPrivilegedAction =
			new PrivilegedAction<MethodDelegation>() {

		@Override
		public MethodDelegation run() {
			return MethodDelegation.to( ProxyConfiguration.InterceptorDispatcher.class );
		}
	};

	this.delegateToInterceptorDispatcherMethodDelegation = System.getSecurityManager() != null
			? AccessController.doPrivileged( delegateToInterceptorDispatcherMethodDelegationPrivilegedAction )
			: delegateToInterceptorDispatcherMethodDelegationPrivilegedAction.run();

	PrivilegedAction<FieldAccessor.PropertyConfigurable> interceptorFieldAccessorPrivilegedAction =
			new PrivilegedAction<FieldAccessor.PropertyConfigurable>() {

		@Override
		public FieldAccessor.PropertyConfigurable run() {
			return FieldAccessor.ofField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME )
					.withAssigner( Assigner.DEFAULT, Assigner.Typing.DYNAMIC );
		}
	};

	this.interceptorFieldAccessor = System.getSecurityManager() != null
			? AccessController.doPrivileged( interceptorFieldAccessorPrivilegedAction )
			: interceptorFieldAccessorPrivilegedAction.run();
}
 
Example #16
Source Project: styx   Author: HotelsDotCom   File: ThrowableSanitiser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Wrap a {@link Throwable} in a dynamic proxy that sanitizes its message to hide sensitive cookie
 * information. The supplied Throwable must be non-final, and must have a no-args constructor. If the proxy
 * cannot be created for any reason (including that it is proxying a final class, or one without a no-args constructor),
 * then a warning is logged and the unproxied Throwable is returned back to the caller.
 * @param original the Throwable to be proxied
 * @param formatter hides the sensitive cookies.
 * @return the proxied Throwable, or the original throwable if it cannot be proxied.
 */
public Throwable sanitise(Throwable original, SanitisedHttpHeaderFormatter formatter) {

    Class<?> clazz = original.getClass();
    try {
        Constructor<?> defaultConstructor = clazz.getConstructor();

        Class<?> proxyClass = typeCache.findOrInsert(getClass().getClassLoader(), clazz.getName(), () ->
                new ByteBuddy()
                        .subclass(clazz)
                        .defineField("methodInterceptor", Interceptor.class, Visibility.PRIVATE)
                        .defineConstructor(Visibility.PUBLIC)
                        .withParameters(Interceptor.class)
                        .intercept(FieldAccessor.ofField("methodInterceptor").setsArgumentAt(0)
                                .andThen(MethodCall.invoke(defaultConstructor)))
                        .method(ElementMatchers.any())
                        .intercept(MethodDelegation.toField("methodInterceptor"))
                        .make()
                        .load(getClass().getClassLoader())
                        .getLoaded());

        return (Throwable) proxyClass
                .getConstructor(Interceptor.class)
                .newInstance(new Interceptor(original, formatter));
    } catch (Exception e) {
        LOG.warn("Unable to proxy throwable class {} - {}", clazz, e.toString()); // No need to log stack trace here
    }
    return original;
}
 
Example #17
Source Project: byte-buddy   Author: raphw   File: ClassByExtensionBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs a benchmark of a class extension using Byte Buddy. This benchmark also uses the annotation-based approach
 * but creates delegation methods which do not require the creation of additional classes. This benchmark uses a type
 * pool to compare against usage of the reflection API.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws Exception If the invocation causes an exception.
 */
@Benchmark
public ExampleClass benchmarkByteBuddyWithAccessorWithTypePool() throws Exception {
    return (ExampleClass) new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .ignore(none())
            .subclass(baseClassDescription)
            .method(isDeclaredBy(baseClassDescription)).intercept(MethodDelegation.to(accessClassDescription))
            .make()
            .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance();
}
 
Example #18
Source Project: flow   Author: vaadin   File: TemplateModelProxyHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static BiFunction<StateNode, BeanModelType<?>, Object> createProxyConstructor(
        ClassLoader classLoader, Builder<?> proxyBuilder, String classFqn) {
    String proxyClassName = generateProxyClassName(classFqn, classLoader);
    Class<?> proxyType = proxyBuilder

            // Handle bean methods (and abstract methods for error handling)
            .method(method -> isAccessor(method) || method.isAbstract())
            .intercept(MethodDelegation.to(proxyHandler))

            // Handle internal $stateNode methods
            .defineField("$stateNode", StateNode.class)
            .method(method -> "$stateNode".equals(method.getName()))
            .intercept(FieldAccessor.ofField("$stateNode"))

            // Handle internal $modelType methods
            .defineField("$modelType", BeanModelType.class)
            .method(method -> "$modelType".equals(method.getName()))
            .intercept(FieldAccessor.ofField("$modelType"))

            // Create the class
            .name(proxyClassName).make()
            .load(classLoader, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();

    return (node, modelType) -> {
        Object instance = ReflectTools.createProxyInstance(proxyType,
                modelType.getProxyType());
        ModelProxy modelProxy = (ModelProxy) instance;
        modelProxy.$stateNode(node);
        modelProxy.$modelType(modelType);

        modelType.createInitialValues(node);
        return instance;
    };
}
 
Example #19
Source Project: byte-buddy   Author: raphw   File: ClassByExtensionBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs a benchmark of a class extension using Byte Buddy. This benchmark uses delegation but completes with a
 * hard-coded super method call. This benchmark uses a type pool to compare against usage of the reflection API.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws Exception If the invocation causes an exception.
 */
@Benchmark
public ExampleClass benchmarkByteBuddyWithPrefixWithTypePool() throws Exception {
    return (ExampleClass) new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .ignore(none())
            .subclass(baseClassDescription)
            .method(isDeclaredBy(baseClassDescription)).intercept(MethodDelegation.to(prefixClassDescription).andThen(SuperMethodCall.INSTANCE))
            .make()
            .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance();
}
 
Example #20
Source Project: activejpa   Author: ActiveJpa   File: ModelClassEnhancer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param builder
 * @param typeDescription
 * @param classLoader
 * @param name
 * @param targetType
 * @param parameters
 * @return
 */
private Builder<?> defineMethod(Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, String name, TypeDefinition targetType, TypeDefinition... parameters) {
    logger.info("Defining the method - {}.{} with return type - {} and parameters - {}", typeDescription.getActualName(), name, targetType.getActualName(), parameters);
    try {
        builder = builder.defineMethod(name, targetType, Ownership.STATIC, Visibility.PUBLIC).withParameters(parameters).intercept(MethodDelegation.to(ModelInterceptor.class));
        builder.make();
    } catch (Exception exception) {
        if (! (exception.getCause() instanceof NoSuchMethodException)) {
            logger.error("Failed while defining the method - {}.{}", typeDescription.getActualName(), name, exception);
            throw new AssertionError(exception);
        }
    }
    return builder;
}
 
Example #21
Source Project: windup   Author: windup   File: JavaHandlerHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private <E> DynamicType.Builder<E> createInterceptor(final DynamicType.Builder<E> builder, final Method method)
    {
//        return builder.method(ElementMatchers.is(method))
//                    .intercept(MethodDelegation.to(JavaHandlerHandler.JavaHandlerInterceptor.class));
        return builder.define(method).intercept(MethodDelegation.to(JavaHandlerHandler.JavaHandlerInterceptor.class))
                .annotateMethod(method.getAnnotations());
    }
 
Example #22
Source Project: tutorials   Author: eugenp   File: ByteBuddyUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {

    String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance()
            .sayHelloFoo();

    assertEquals(r, Bar.sayHelloBar());
}
 
Example #23
Source Project: byte-buddy   Author: raphw   File: ClassByExtensionBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs a benchmark of a class extension using Byte Buddy. This benchmark uses delegation but completes with a
 * hard-coded super method call.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws Exception If the invocation causes an exception.
 */
@Benchmark
public ExampleClass benchmarkByteBuddyWithPrefix() throws Exception {
    return new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .ignore(none())
            .subclass(baseClass)
            .method(isDeclaredBy(baseClass)).intercept(MethodDelegation.to(ByteBuddyPrefixInterceptor.class).andThen(SuperMethodCall.INSTANCE))
            .make()
            .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance();
}
 
Example #24
Source Project: byte-buddy   Author: raphw   File: AgentBuilderDefaultApplicationTest.java    License: Apache License 2.0 5 votes vote down vote up
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
                                        TypeDescription typeDescription,
                                        ClassLoader classLoader,
                                        JavaModule module) {
    try {
        return builder.method(named(FOO)).intercept(MethodDelegation.to(new Interceptor()));
    } catch (Exception exception) {
        throw new AssertionError(exception);
    }
}
 
Example #25
Source Project: byte-buddy   Author: raphw   File: AgentBuilderDefaultApplicationTest.java    License: Apache License 2.0 5 votes vote down vote up
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
                                        TypeDescription typeDescription,
                                        ClassLoader classLoader,
                                        JavaModule module) {
    try {
        return builder.method(named(FOO)).intercept(MethodDelegation.to(new Interceptor()));
    } catch (Exception exception) {
        throw new AssertionError(exception);
    }
}
 
Example #26
Source Project: byte-buddy   Author: raphw   File: AgentBuilderDefaultApplicationTest.java    License: Apache License 2.0 5 votes vote down vote up
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
                                        TypeDescription typeDescription,
                                        ClassLoader classLoader,
                                        JavaModule module) {
    try {
        return builder.method(named(FOO)).intercept(MethodDelegation.to(new Interceptor()));
    } catch (Exception exception) {
        throw new AssertionError(exception);
    }
}
 
Example #27
Source Project: byte-buddy   Author: raphw   File: ByteBuddyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeInitializerInstrumentation() throws Exception {
    Recorder recorder = new Recorder();
    Class<?> type = new ByteBuddy()
            .subclass(Object.class)
            .invokable(isTypeInitializer())
            .intercept(MethodDelegation.to(recorder))
            .make(new TypeResolutionStrategy.Active())
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredConstructor().newInstance(), instanceOf(type));
    assertThat(recorder.counter, is(1));
}
 
Example #28
@Test
public void testTypeDescription() throws Exception {
    assertThat(new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, TypeDescription.OBJECT))
                    .to(Foo.class))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .foo(), is((Object) Object.class));
}
 
Example #29
@Test
public void testNull() throws Exception {
    assertThat(new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, null))
                    .to(Foo.class))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .foo(), nullValue(Object.class));
}
 
Example #30
@Test(expected = IllegalStateException.class)
public void testIllegalArgument() throws Exception {
    new ByteBuddy()
            .subclass(Foo.class)
            .method(named(FOO))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of(Bar.class, new Object()))
                    .to(Foo.class))
            .make();
}