Class.forName(byteBuddy.subclass(Object.class) .name(String.format("%s$%s$%d", source.getName(), "MockitoModuleProbe", Math.abs(random.nextInt()))) .invokable(isTypeInitializer()).intercept(implementation) .make() .load(source.getClassLoader(), loader.resolveStrategy(source, source.getClassLoader(), false))
/** * {@inheritDoc} */ public DynamicType make(String auxiliaryTypeName, ClassFileVersion classFileVersion, MethodAccessorFactory methodAccessorFactory) { Implementation.Composable constructor = MethodCall.invoke(DEFAULT_CONSTRUCTOR).andThen(FieldAccessor.ofField(TYPE_FIELD).setsArgumentAt(0)); int index = 1; for (String field : fields.keySet()) { constructor = constructor.andThen(FieldAccessor.ofField(field).setsArgumentAt(index++)); } DynamicType.Builder<?> builder = new ByteBuddy(classFileVersion) .with(TypeValidation.DISABLED) .subclass(PrivilegedExceptionAction.class, ConstructorStrategy.Default.NO_CONSTRUCTORS) .name(auxiliaryTypeName) .modifiers(DEFAULT_TYPE_MODIFIER) .defineConstructor(Visibility.PUBLIC) .withParameters(CompoundList.of(Class.class, new ArrayList<Class<?>>(fields.values()))) .intercept(constructor) .method(named("run")) .intercept(MethodCall.invoke(methodDescription) .onField(TYPE_FIELD) .withField(fields.keySet().toArray(new String[fields.size()]))) .defineField(TYPE_FIELD, Class.class, Visibility.PRIVATE); for (Map.Entry<String, Class<?>> entry : fields.entrySet()) { builder = builder.defineField(entry.getKey(), entry.getValue(), Visibility.PRIVATE); } return builder.make(); } }
.name(ExecutingTransformer.class.getName() + "$ByteBuddy$ModuleSupport") .method(named("transform").and(takesArgument(0, JavaType.MODULE.load()))) .intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform", Object.class, ClassLoader.class,
.or(ElementMatchers.named("isPhantom")) .or(ElementMatchers.named("delete")))) .intercept(MethodDelegation.withDefaultConfiguration() .withBinders(FieldProxy.Binder .install(LiveObjectInterceptor.Getter.class, .and(ElementMatchers.named("get") .or(ElementMatchers.named("set")))) .intercept(MethodDelegation.to(FieldAccessorInterceptor.class)) .intercept(MethodDelegation.to(RObjectInterceptor.class)) .implement(RObject.class) .intercept(MethodDelegation.to(RExpirableInterceptor.class)) .implement(RExpirable.class) .or(ElementMatchers.isDeclaredBy(RMapAsync.class)) .or(ElementMatchers.isDeclaredBy(RMap.class))) .intercept(MethodDelegation.to(RMapInterceptor.class)) .implement(RMap.class) .or(ElementMatchers.isProtected())) .intercept(MethodDelegation.to(new AccessorInterceptor(redisson, commandExecutor.getObjectBuilder())))
@Override public <T> T newProxy(Class<T> interfaceType, Object handler) { Class<? extends T> cls = new ByteBuddy() .subclass(interfaceType) .method(ElementMatchers.isDeclaredBy(interfaceType)) .intercept(MethodDelegation.to(handler, "handler")) .make() .load(interfaceType.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded(); try { return cls.newInstance(); } catch (Throwable t) { ThrowUtil.throwException(t); } return null; // never get here } });
@Override public <T> T newProxy(Class<T> interfaceType, Object handler) { Class<? extends T> cls = new ByteBuddy() .subclass(interfaceType) .method(ElementMatchers.isDeclaredBy(interfaceType)) .intercept(MethodDelegation.to(handler, "handler")) .make() .load(interfaceType.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded(); try { return cls.newInstance(); } catch (Throwable t) { ThrowUtil.throwException(t); } return null; // never get here } });
@SuppressWarnings({ "unchecked", "rawtypes" }) public Class buildProxy( final Class persistentClass, final Class[] interfaces) { Set<Class<?>> key = new HashSet<Class<?>>(); if ( interfaces.length == 1 ) { key.add( persistentClass ); } key.addAll( Arrays.<Class<?>>asList( interfaces ) ); return byteBuddyState.loadProxy( persistentClass, new TypeCache.SimpleKey(key), byteBuddy -> byteBuddy .ignore( byteBuddyState.getProxyDefinitionHelpers().getGroovyGetMetaClassFilter() ) .with( new NamingStrategy.SuffixingRandom( PROXY_NAMING_SUFFIX, new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( persistentClass.getName() ) ) ) .subclass( interfaces.length == 1 ? persistentClass : Object.class, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING ) .implement( (Type[]) interfaces ) .method( byteBuddyState.getProxyDefinitionHelpers().getVirtualNotFinalizerFilter() ) .intercept( byteBuddyState.getProxyDefinitionHelpers().getDelegateToInterceptorDispatcherMethodDelegation() ) .method( byteBuddyState.getProxyDefinitionHelpers().getHibernateGeneratedMethodFilter() ) .intercept( SuperMethodCall.INSTANCE ) .defineField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME, ProxyConfiguration.Interceptor.class, Visibility.PRIVATE ) .implement( ProxyConfiguration.class ) .intercept( byteBuddyState.getProxyDefinitionHelpers().getInterceptorFieldAccessor() ) ); }
Enhance enhance = typeDescription.getDeclaredAnnotations().ofType(Enhance.class).loadSilent(); if (typeDescription.getDeclaredMethods().filter(isHashCode()).isEmpty()) { builder = builder.method(isHashCode()).intercept(enhance.invokeSuper() .hashCodeMethod(typeDescription) .withIgnoredFields(enhance.includeSyntheticFields() .withStringTypedFieldsFirst(); builder = builder.method(isEquals()).intercept(enhance.permitSubclassEquality() ? equalsMethod.withSubclassEquality() : equalsMethod);
@SuppressWarnings({ "unchecked", "rawtypes" }) public BasicProxyFactoryImpl(Class superClass, Class[] interfaces, ByteBuddyState byteBuddyState) { if ( superClass == null && ( interfaces == null || interfaces.length < 1 ) ) { throw new AssertionFailure( "attempting to build proxy without any superclass or interfaces" ); } final Class<?> superClassOrMainInterface = superClass != null ? superClass : interfaces[0]; final TypeCache.SimpleKey cacheKey = getCacheKey( superClass, interfaces ); this.proxyClass = byteBuddyState.loadBasicProxy( superClassOrMainInterface, cacheKey, byteBuddy -> byteBuddy .with( new NamingStrategy.SuffixingRandom( PROXY_NAMING_SUFFIX, new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( superClassOrMainInterface.getName() ) ) ) .subclass( superClass == null ? Object.class : superClass, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR ) .implement( interfaces == null ? NO_INTERFACES : interfaces ) .defineField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME, ProxyConfiguration.Interceptor.class, Visibility.PRIVATE ) .method( byteBuddyState.getProxyDefinitionHelpers().getVirtualNotFinalizerFilter() ) .intercept( byteBuddyState.getProxyDefinitionHelpers().getDelegateToInterceptorDispatcherMethodDelegation() ) .implement( ProxyConfiguration.class ) .intercept( byteBuddyState.getProxyDefinitionHelpers().getInterceptorFieldAccessor() ) ); this.interceptor = new PassThroughInterceptor( proxyClass.getName() ); }
private static Object crateForParameters(Class<?> effectiveTargetClass, Set<Class<?>> interfacesToImplement, ClassLoader classLoader, Class<?> interceptorClass) { List<Type> interfacesToImplementAsList = new ArrayList<Type>(interfacesToImplement); Class<?> proxyType = new ByteBuddy() .subclass(effectiveTargetClass) .implement(interfacesToImplementAsList) .method(not(isFinalizer())) .intercept(MethodDelegation.to(interceptorClass)) .make() .load(classLoader) .getLoaded(); return instantiate(proxyType); }
public static <E> E createInstance(Class<E> entityClass) { Class<? extends E> loaded = new ByteBuddy() .subclass( entityClass ) .method( ElementMatchers.named( "toString" ) ) .intercept( FixedValue.value( "transformed" ) ) .make() // we use our internal helper to get a class loading strategy suitable for the JDK used .load( entityClass.getClassLoader(), resolveClassLoadingStrategy( entityClass ) ) .getLoaded(); try { return loaded.newInstance(); } catch (Exception e) { throw new RuntimeException( "Unable to create new instance of " + entityClass.getSimpleName(), e ); } }
/** * {@inheritDoc} */ public DynamicType make(String auxiliaryTypeName, ClassFileVersion classFileVersion, MethodAccessorFactory methodAccessorFactory) { return new ByteBuddy(classFileVersion) .with(TypeValidation.DISABLED) .subclass(morphingType, ConstructorStrategy.Default.NO_CONSTRUCTORS) .name(auxiliaryTypeName) .modifiers(DEFAULT_TYPE_MODIFIER) .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0]) .defineConstructor().withParameters(specialMethodInvocation.getMethodDescription().isStatic() ? Collections.<TypeDescription>emptyList() : Collections.singletonList(instrumentedType)) .intercept(specialMethodInvocation.getMethodDescription().isStatic() ? StaticFieldConstructor.INSTANCE : new InstanceFieldConstructor(instrumentedType)) .method(ElementMatchers.<MethodDescription>isAbstract().and(isDeclaredBy(morphingType))) .intercept(new MethodCall(methodAccessorFactory.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT), assigner)) .make(); }
/** * {@inheritDoc} */ public DynamicType make(String auxiliaryTypeName, ClassFileVersion classFileVersion, MethodAccessorFactory methodAccessorFactory) { LinkedHashMap<String, TypeDescription> parameterFields = extractFields(sourceMethod); DynamicType.Builder<?> builder = new ByteBuddy(classFileVersion) .with(TypeValidation.DISABLED) .subclass(forwardingType, ConstructorStrategy.Default.NO_CONSTRUCTORS) .name(auxiliaryTypeName) .modifiers(DEFAULT_TYPE_MODIFIER) .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0]) .method(ElementMatchers.<MethodDescription>isAbstract().and(isDeclaredBy(forwardingType))) .intercept(new MethodCall(sourceMethod, assigner)) .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(); }
/** * {@inheritDoc} */ public DynamicType make(String auxiliaryTypeName, ClassFileVersion classFileVersion, MethodAccessorFactory methodAccessorFactory) { return new ByteBuddy(classFileVersion) .with(TypeValidation.DISABLED) .ignore(ignoreFinalizer ? isFinalizer() : ElementMatchers.<MethodDescription>none()) .subclass(proxiedType) .name(auxiliaryTypeName) .modifiers(DEFAULT_TYPE_MODIFIER) .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0]) .method(any()).intercept(new MethodCall(methodAccessorFactory)) .defineMethod(REFLECTION_METHOD, TargetType.class, Ownership.STATIC).intercept(SilentConstruction.INSTANCE) .make(); }
/** * {@inheritDoc} */ public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassFileLocator classFileLocator) { Enhance enhance = typeDescription.getDeclaredAnnotations().ofType(Enhance.class).loadSilent(); if (typeDescription.getDeclaredMethods().filter(isToString()).isEmpty()) { builder = builder.method(isToString()).intercept(ToStringMethod.prefixedBy(enhance.prefix().getPrefixResolver()) .withIgnoredFields(enhance.includeSyntheticFields() ? ElementMatchers.<FieldDescription>none() : ElementMatchers.<FieldDescription>isSynthetic()) .withIgnoredFields(isAnnotatedWith(Exclude.class))); } return builder; }
/** * {@inheritDoc} */ public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, FieldDescription fieldDescription, Assigner assigner, MethodAccessorFactory methodAccessorFactory) { return builder .method(is(getterMethod)).intercept(new FieldGetter(fieldDescription, assigner, methodAccessorFactory)) .method(is(setterMethod)).intercept(fieldDescription.isFinal() ? ExceptionMethod.throwing(UnsupportedOperationException.class, "Cannot set final field " + fieldDescription) : new FieldSetter(fieldDescription, assigner, methodAccessorFactory)); } }
/** * {@inheritDoc} */ public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, FieldDescription fieldDescription, Assigner assigner, MethodAccessorFactory methodAccessorFactory) { return builder.method(is(setterMethod)).intercept(new FieldSetter(fieldDescription, assigner, methodAccessorFactory)); } }
/** * {@inheritDoc} */ public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, FieldDescription fieldDescription, Assigner assigner, MethodAccessorFactory methodAccessorFactory) { return builder.method(definedMethod(is(getterMethod))).intercept(new FieldGetter(fieldDescription, assigner, methodAccessorFactory)); } }
/** * {@inheritDoc} */ public Builder<S> withToString() { return method(isToString()).intercept(ToStringMethod.prefixedBySimpleClassName()); }