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 File: RSocketRemoteServiceBuilder.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@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 File: ByteBuddyStageClassCreator.java From JGiven with Apache License 2.0 | 6 votes |
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 #3
Source File: RebaseDynamicTypeBuilderTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@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 #4
Source File: BytebuddyProxy.java From sofa-rpc with Apache License 2.0 | 6 votes |
@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 #5
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@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 #6
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@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 #7
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@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 #8
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@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 #9
Source File: MethodCaptor.java From reflection-util with Apache License 2.0 | 6 votes |
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 #10
Source File: ByteBuddyUnitTest.java From tutorials with MIT License | 5 votes |
@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 #11
Source File: ByteBuddyTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@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 #12
Source File: JavaHandlerHandler.java From windup with Eclipse Public License 1.0 | 5 votes |
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 #13
Source File: ModelClassEnhancer.java From activejpa with Apache License 2.0 | 5 votes |
/** * @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 #14
Source File: ClassByExtensionBenchmark.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * 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 #15
Source File: ThrowableSanitiser.java From styx with Apache License 2.0 | 5 votes |
/** * 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 #16
Source File: RevisedCapabilityMatcher.java From Selenium-Foundation with Apache License 2.0 | 5 votes |
/** * 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 #17
Source File: ServiceOrchestratorLoader.java From yanwte2 with Apache License 2.0 | 5 votes |
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 #18
Source File: ByteBuddyState.java From lams with GNU General Public License v2.0 | 5 votes |
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 #19
Source File: ClassByExtensionBenchmark.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * 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 #20
Source File: ClassByExtensionBenchmark.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * 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 #21
Source File: AgentBuilderDefaultApplicationTest.java From byte-buddy with Apache License 2.0 | 5 votes |
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 #22
Source File: AgentBuilderDefaultApplicationTest.java From byte-buddy with Apache License 2.0 | 5 votes |
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 #23
Source File: AgentBuilderDefaultApplicationTest.java From byte-buddy with Apache License 2.0 | 5 votes |
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 #24
Source File: ByteBuddyProxyTest.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
@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 #25
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@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 #26
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@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 #27
Source File: TargetMethodAnnotationDriverBinderParameterBinderForFixedValueOfConstantOtherTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@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(); }
Example #28
Source File: ClassInjectorUsingReflectionTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test @ClassReflectionInjectionAvailableRule.Enforce public void testInjectionOrderNoPrematureAuxiliaryInjection() throws Exception { ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(Bar.class, Interceptor.class)); Class<?> type = new ByteBuddy() .rebase(Bar.class) .method(named(BAR)) .intercept(MethodDelegation.to(Interceptor.class)).make() .load(classLoader, ClassLoadingStrategy.Default.INJECTION) .getLoaded(); assertThat(type.getDeclaredMethod(BAR, String.class).invoke(type.getDeclaredConstructor().newInstance(), FOO), is((Object) BAR)); }
Example #29
Source File: ClassByExtensionBenchmark.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * Performs a benchmark of a class extension using Byte Buddy. This benchmark creates proxy classes for the invocation * of super methods which requires the creation of auxiliary 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 java.lang.Exception If the invocation causes an exception. */ @Benchmark public ExampleClass benchmarkByteBuddyWithProxyWithTypePool() throws Exception { return (ExampleClass) new ByteBuddy() .with(TypeValidation.DISABLED) .ignore(none()) .subclass(baseClassDescription) .method(isDeclaredBy(baseClassDescription)).intercept(MethodDelegation.to(proxyClassDescription)) .make() .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .getDeclaredConstructor() .newInstance(); }
Example #30
Source File: ClassByExtensionBenchmark.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * 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. * * @return The created instance, in order to avoid JIT removal. * @throws Exception If the invocation causes an exception. */ @Benchmark public ExampleClass benchmarkByteBuddyWithAccessor() throws Exception { return new ByteBuddy() .with(TypeValidation.DISABLED) .ignore(none()) .subclass(baseClass) .method(isDeclaredBy(baseClass)).intercept(MethodDelegation.to(ByteBuddyAccessInterceptor.class)) .make() .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .getDeclaredConstructor() .newInstance(); }