Class Enhancer
- java.lang.Object
- org.springframework.cglib.core.AbstractClassGenerator
- org.springframework.cglib.proxy.Enhancer
- All Implemented Interfaces:
org.springframework.cglib.core.ClassGenerator
public class Enhancer extends AbstractClassGenerator
Generates dynamic subclasses to enable method interception. This class started as a substitute for the standard Dynamic Proxy support included with JDK 1.3, but one that allowed the proxies to extend a concrete base class, in addition to implementing interfaces. The dynamically generated subclasses override the non-final methods of the superclass and have hooks which callback to user-defined interceptor implementations.The original and most general callback type is the
MethodInterceptor
, which in AOP terms enables "around advice"--that is, you can invoke custom code both before and after the invocation of the "super" method. In addition you can modify the arguments before calling the super method, or not call it at all.Although
MethodInterceptor
is generic enough to meet any interception need, it is often overkill. For simplicity and performance, additional specialized callback types, such asLazyLoader
are also available. Often a single callback will be used per enhanced class, but you can control which callback is used on a per-method basis with aCallbackFilter
.The most common uses of this class are embodied in the static helper methods. For advanced needs, such as customizing the
ClassLoader
to use, you should create a new instance ofEnhancer
. Other classes within CGLIB follow a similar pattern.All enhanced objects implement the
Factory
interface, unlesssetUseFactory(boolean)
is used to explicitly disable this feature. TheFactory
interface provides an API to change the callbacks of an existing object, as well as a faster and easier way to create new instances of the same type.For an almost drop-in replacement for
java.lang.reflect.Proxy
, see theProxy
class.
Nested Class Summary
Nested Classes Modifier and Type Class Description static interface
Enhancer.EnhancerKey
Internal interface, only public due to ClassLoader issues.Nested classes/interfaces inherited from class org.springframework.cglib.core.AbstractClassGenerator
AbstractClassGenerator.ClassLoaderData, AbstractClassGenerator.Source
Constructor Summary
Constructors Constructor Description Enhancer()
Create a newEnhancer
.
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description Object
create()
Generate a new class if necessary and uses the specified callbacks (if any) to create a new object instance.Object
create(Class[] argumentTypes, Object[] arguments)
Generate a new class if necessary and uses the specified callbacks (if any) to create a new object instance.static Object
create(Class superclass, Class[] interfaces, org.springframework.cglib.proxy.Callback callback)
Helper method to create an intercepted object.static Object
create(Class superclass, Class[] interfaces, org.springframework.cglib.proxy.CallbackFilter filter, org.springframework.cglib.proxy.Callback[] callbacks)
Helper method to create an intercepted object.static Object
create(Class type, org.springframework.cglib.proxy.Callback callback)
Helper method to create an intercepted object.Class
createClass()
Generate a new class if necessary and return it without creating a new instance.protected void
filterConstructors(Class sc, List constructors)
Filter the list of constructors from the superclass.protected Object
firstInstance(Class type)
This method should not be called in regular flow.protected Class
generate(AbstractClassGenerator.ClassLoaderData data)
void
generateClass(ClassVisitor v)
protected ClassLoader
getDefaultClassLoader()
static void
getMethods(Class superclass, Class[] interfaces, List methods)
Finds all of the methods that will be extended by an Enhancer-generated class using the specified superclass and interfaces.protected ProtectionDomain
getProtectionDomain()
Returns the protection domain to use when defining the class.static boolean
isEnhanced(Class type)
Determine if a class was generated usingEnhancer
.protected Object
nextInstance(Object instance)
static void
registerCallbacks(Class generatedClass, org.springframework.cglib.proxy.Callback[] callbacks)
Call this method to register theCallback
array to use before creating a new instance of the generated class via reflection.static void
registerStaticCallbacks(Class generatedClass, org.springframework.cglib.proxy.Callback[] callbacks)
Similar toregisterCallbacks(java.lang.Class, org.springframework.cglib.proxy.Callback[])
, but suitable for use when multiple threads will be creating instances of the generated class.void
setCallback(org.springframework.cglib.proxy.Callback callback)
Set the singleCallback
to use.void
setCallbackFilter(org.springframework.cglib.proxy.CallbackFilter filter)
Set theCallbackFilter
used to map the generated class' methods to a particular callback index.void
setCallbacks(org.springframework.cglib.proxy.Callback[] callbacks)
Set the array of callbacks to use.void
setCallbackType(Class callbackType)
Set the single type ofCallback
to use.void
setCallbackTypes(Class[] callbackTypes)
Set the array of callback types to use.void
setInterceptDuringConstruction(boolean interceptDuringConstruction)
Set whether methods called from within the proxy's constructer will be intercepted.void
setInterfaces(Class[] interfaces)
Set the interfaces to implement.void
setSerialVersionUID(Long sUID)
Insert a static serialVersionUID field into the generated class.void
setSuperclass(Class superclass)
Set the class which the generated class will extend.void
setUseFactory(boolean useFactory)
Set whether the enhanced object instances should implement theFactory
interface.protected Object
unwrapCachedValue(Object cached)
protected Object
wrapCachedClass(Class klass)
Methods inherited from class org.springframework.cglib.core.AbstractClassGenerator
create, getAttemptLoad, getClassLoader, getClassName, getCurrent, getNamingPolicy, getStrategy, getUseCache, setAttemptLoad, setClassLoader, setContextClass, setNamePrefix, setNamingPolicy, setStrategy, setUseCache
Constructor Detail
Enhancer
public Enhancer()
Create a newEnhancer
. A newEnhancer
object should be used for each generated object, and should not be shared across threads. To create additional instances of a generated class, use theFactory
interface.- See Also:
Factory
Method Detail
setSuperclass
public void setSuperclass(Class superclass)
Set the class which the generated class will extend. As a convenience, if the supplied superclass is actually an interface,setInterfaces
will be called with the appropriate argument instead. A non-interface argument must not be declared as final, and must have an accessible constructor.- Parameters:
superclass
- class to extend or interface to implement- See Also:
setInterfaces(Class[])
setInterfaces
public void setInterfaces(Class[] interfaces)
Set the interfaces to implement. TheFactory
interface will always be implemented regardless of what is specified here.- Parameters:
interfaces
- array of interfaces to implement, or null- See Also:
Factory
setCallbackFilter
public void setCallbackFilter(org.springframework.cglib.proxy.CallbackFilter filter)
Set theCallbackFilter
used to map the generated class' methods to a particular callback index. New object instances will always use the same mapping, but may use different actual callback objects.- Parameters:
filter
- the callback filter to use when generating a new class- See Also:
setCallbacks(org.springframework.cglib.proxy.Callback[])
setCallback
public void setCallback(org.springframework.cglib.proxy.Callback callback)
Set the singleCallback
to use. Ignored if you usecreateClass()
.- Parameters:
callback
- the callback to use for all methods- See Also:
setCallbacks(org.springframework.cglib.proxy.Callback[])
setCallbacks
public void setCallbacks(org.springframework.cglib.proxy.Callback[] callbacks)
Set the array of callbacks to use. Ignored if you usecreateClass()
. You must use aCallbackFilter
to specify the index into this array for each method in the proxied class.- Parameters:
callbacks
- the callback array- See Also:
setCallbackFilter(org.springframework.cglib.proxy.CallbackFilter)
,setCallback(org.springframework.cglib.proxy.Callback)
setUseFactory
public void setUseFactory(boolean useFactory)
Set whether the enhanced object instances should implement theFactory
interface. This was added for tools that need for proxies to be more indistinguishable from their targets. Also, in some cases it may be necessary to disable theFactory
interface to prevent code from changing the underlying callbacks.- Parameters:
useFactory
- whether to implementFactory
; default istrue
setInterceptDuringConstruction
public void setInterceptDuringConstruction(boolean interceptDuringConstruction)
Set whether methods called from within the proxy's constructer will be intercepted. The default value is true. Unintercepted methods will call the method of the proxy's base class, if it exists.- Parameters:
interceptDuringConstruction
- whether to intercept methods called from the constructor
setCallbackType
public void setCallbackType(Class callbackType)
Set the single type ofCallback
to use. This may be used instead ofsetCallback(org.springframework.cglib.proxy.Callback)
when callingcreateClass()
, since it may not be possible to have an array of actual callback instances.- Parameters:
callbackType
- the type of callback to use for all methods- See Also:
setCallbackTypes(java.lang.Class[])
setCallbackTypes
public void setCallbackTypes(Class[] callbackTypes)
Set the array of callback types to use. This may be used instead ofsetCallbacks(org.springframework.cglib.proxy.Callback[])
when callingcreateClass()
, since it may not be possible to have an array of actual callback instances. You must use aCallbackFilter
to specify the index into this array for each method in the proxied class.- Parameters:
callbackTypes
- the array of callback types
create
public Object create()
Generate a new class if necessary and uses the specified callbacks (if any) to create a new object instance. Uses the no-arg constructor of the superclass.- Returns:
- a new instance
create
public Object create(Class[] argumentTypes, Object[] arguments)
Generate a new class if necessary and uses the specified callbacks (if any) to create a new object instance. Uses the constructor of the superclass matching theargumentTypes
parameter, with the given arguments.- Parameters:
argumentTypes
- constructor signaturearguments
- compatible wrapped arguments to pass to constructor- Returns:
- a new instance
createClass
public Class createClass()
Generate a new class if necessary and return it without creating a new instance. This ignores any callbacks that have been set. To create a new instance you will have to use reflection, and methods called during the constructor will not be intercepted. To avoid this problem, use the multi-argcreate
method.- See Also:
create(Class[], Object[])
setSerialVersionUID
public void setSerialVersionUID(Long sUID)
Insert a static serialVersionUID field into the generated class.- Parameters:
sUID
- the field value, or null to avoid generating field.
generate
protected Class generate(AbstractClassGenerator.ClassLoaderData data)
- Overrides:
generate
in classAbstractClassGenerator
getDefaultClassLoader
protected ClassLoader getDefaultClassLoader()
- Specified by:
getDefaultClassLoader
in classAbstractClassGenerator
getProtectionDomain
protected ProtectionDomain getProtectionDomain()
Description copied from class:AbstractClassGenerator
Returns the protection domain to use when defining the class.Default implementation returns
null
for using a default protection domain. Sub-classes may override to use a more specific protection domain.- Overrides:
getProtectionDomain
in classAbstractClassGenerator
- Returns:
- the protection domain (
null
for using a default)
getMethods
public static void getMethods(Class superclass, Class[] interfaces, List methods)
Finds all of the methods that will be extended by an Enhancer-generated class using the specified superclass and interfaces. This can be useful in building a list of Callback objects. The methods are added to the end of the given list. Due to the subclassing nature of the classes generated by Enhancer, the methods are guaranteed to be non-static, non-final, and non-private. Each method signature will only occur once, even if it occurs in multiple classes.- Parameters:
superclass
- the class that will be extended, or nullinterfaces
- the list of interfaces that will be implemented, or nullmethods
- the list into which to copy the applicable methods
generateClass
public void generateClass(ClassVisitor v) throws Exception
- Throws:
Exception
filterConstructors
protected void filterConstructors(Class sc, List constructors)
Filter the list of constructors from the superclass. The constructors which remain will be included in the generated class. The default implementation is to filter out all private constructors, but subclasses may extend Enhancer to override this behavior.- Parameters:
sc
- the superclassconstructors
- the list of all declared constructors from the superclass- Throws:
IllegalArgumentException
- if there are no non-private constructors
firstInstance
protected Object firstInstance(Class type) throws Exception
This method should not be called in regular flow. Technically speakingwrapCachedClass(Class)
usesEnhancer.EnhancerFactoryData
as a cache value, and the latter enables faster instantiation than plain old reflection lookup and invoke. This method is left intact for backward compatibility reasons: just in case it was ever used.- Specified by:
firstInstance
in classAbstractClassGenerator
- Parameters:
type
- class to instantiate- Returns:
- newly created proxy instance
- Throws:
Exception
- if something goes wrong
nextInstance
protected Object nextInstance(Object instance)
- Specified by:
nextInstance
in classAbstractClassGenerator
wrapCachedClass
protected Object wrapCachedClass(Class klass)
- Overrides:
wrapCachedClass
in classAbstractClassGenerator
unwrapCachedValue
protected Object unwrapCachedValue(Object cached)
- Overrides:
unwrapCachedValue
in classAbstractClassGenerator
registerCallbacks
public static void registerCallbacks(Class generatedClass, org.springframework.cglib.proxy.Callback[] callbacks)
Call this method to register theCallback
array to use before creating a new instance of the generated class via reflection. If you are using an instance ofEnhancer
or theFactory
interface to create new instances, this method is unnecessary. Its primary use is for when you want to cache and reuse a generated class yourself, and the generated class does not implement theFactory
interface.Note that this method only registers the callbacks on the current thread. If you want to register callbacks for instances created by multiple threads, use
registerStaticCallbacks(java.lang.Class, org.springframework.cglib.proxy.Callback[])
.The registered callbacks are overwritten and subsequently cleared when calling any of the
create
methods (such ascreate()
), or anyFactory
newInstance
method. Otherwise they are not cleared, and you should be careful to set them back tonull
after creating new instances via reflection if memory leakage is a concern.- Parameters:
generatedClass
- a class previously created byEnhancer
callbacks
- the array of callbacks to use when instances of the generated class are created- See Also:
setUseFactory(boolean)
registerStaticCallbacks
public static void registerStaticCallbacks(Class generatedClass, org.springframework.cglib.proxy.Callback[] callbacks)
Similar toregisterCallbacks(java.lang.Class, org.springframework.cglib.proxy.Callback[])
, but suitable for use when multiple threads will be creating instances of the generated class. The thread-level callbacks will always override the static callbacks. Static callbacks are never cleared.- Parameters:
generatedClass
- a class previously created byEnhancer
callbacks
- the array of callbacks to use when instances of the generated class are created
isEnhanced
public static boolean isEnhanced(Class type)
Determine if a class was generated usingEnhancer
.- Parameters:
type
- any class- Returns:
- whether the class was generated using
Enhancer
create
public static Object create(Class type, org.springframework.cglib.proxy.Callback callback)
Helper method to create an intercepted object. For finer control over the generated instance, use a new instance ofEnhancer
instead of this static method.- Parameters:
type
- class to extend or interface to implementcallback
- the callback to use for all methods
create
public static Object create(Class superclass, Class[] interfaces, org.springframework.cglib.proxy.Callback callback)
Helper method to create an intercepted object. For finer control over the generated instance, use a new instance ofEnhancer
instead of this static method.- Parameters:
superclass
- class to extend or interface to implementinterfaces
- array of interfaces to implement, or nullcallback
- the callback to use for all methods
create
public static Object create(Class superclass, Class[] interfaces, org.springframework.cglib.proxy.CallbackFilter filter, org.springframework.cglib.proxy.Callback[] callbacks)
Helper method to create an intercepted object. For finer control over the generated instance, use a new instance ofEnhancer
instead of this static method.- Parameters:
superclass
- class to extend or interface to implementinterfaces
- array of interfaces to implement, or nullfilter
- the callback filter to use when generating a new classcallbacks
- callback implementations to use for the enhanced object