@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) private static < CT , I > Function < CT , I > createFunction ( Class < CT > contextType , Class < I > typeToExtend , Map < Method , MethodInvocationHandler < CT > > invokers ) { try { DynamicType . Builder builder = new ByteBuddy ( ) . subclass ( typeToExtend ) ; // Add the context field builder = builder . defineField ( "context" , contextType , Visibility . PRIVATE ) ; // Add the constructor builder = builder . defineConstructor ( Visibility . PUBLIC ) . withParameter ( contextType ) . intercept ( MethodCall . invoke ( Object . class . getDeclaredConstructor ( ) ) . onSuper ( ) . andThen ( FieldAccessor . ofField ( "context" ) . setsArgumentAt ( 0 ) ) ) ; // TODO: The constructor needs to support abstract base classes and injection via InstanceFactory for ( Map . Entry < Method , MethodInvocationHandler < CT > > e : invokers . entrySet ( ) ) { builder = builder . define ( e . getKey ( ) ) . intercept ( MethodDelegation . to ( new Runner ( e . getValue ( ) ) ) ) ; } Class createdClass = builder . make ( ) . load ( typeToExtend . getClassLoader ( ) ) . getLoaded ( ) ; return createFactory ( createdClass , contextType ) ; } catch ( Throwable e ) { if ( e instanceof ProxyException ) throw ( ProxyException ) e ; throw new ProxyException ( e ) ; } }
Create the actual function that creates instances .