LazyLoader: Even though the LazyLoader's only method has the same method signature as FixedValue, the LazyLoader is fundamentally different to the FixedValue interceptor. The LazyLoader is actually supposed to return an instance of a subclass of the enhanced class. This instance is requested only when a method is called on the enhanced object and then stored for future invocations of the generated proxy. This makes sense if your object is expensive in its creation without knowing if the object will ever be used. Be aware that some constructor of the enhanced class must be called both for the proxy object and for the lazily loaded object. Thus, make sure that there is another cheap (maybe protected) constructor available or use an interface type for the proxy. You can choose the invoked constructed by supplying arguments to Enhancer#create(Object...)
exp:
LoaderBean.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class LoaderBean { private String loaderName; private int loaderValue; private PropertyBean propertyBean; public LoaderBean(){ this.loaderName="loaderNameA"; this.loaderValue=123; this.propertyBean=createPropertyBean(); } protected PropertyBean createPropertyBean(){ Enhancer enhancer=new Enhancer(); enhancer.setSuperclass(PropertyBean.class); return (PropertyBean)enhancer.create(PropertyBean.class,new ConcreteClassLazyLoader()); } //setter/getter... }
PropertyBean.java
1 2 3 4 5 6
public class PropertyBean { private String propertyName; private int propertyValue; //setter/getter }
LazyLoader
1 2 3 4 5 6 7 8 9
public class ConcreteClassLazyLoader implements LazyLoader{ public Object loadObject() throws Exception { System.out.println("LazyLoader loadObject() ..."); PropertyBean bean=new PropertyBean(); bean.setPropertyName("lazy-load object propertyName!"); bean.setPropertyValue(11); return bean; } }
负责把执行的方法映射到对应的回调。 int accept(Method method);返回callback数组的序号。由setCallbacks(Callback[] callbacks)设置
exp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class ConcreteClassNoInterface { public String getConcreteMethodA(String str){ System.out.println("ConcreteMethod A ... "+str); return str; } public int getConcreteMethodB(int n){ System.out.println("ConcreteMethod B ... "+n); return n+10; } public int getConcreteMethodFixedValue(int n){ System.out.println("getConcreteMethodFixedValue..."+n); return n+10; } }
1 2 3 4 5 6 7 8 9 10 11 12
public class ConcreteClassCallbackFilter implements CallbackFilter{ public int accept(Method method) { if("getConcreteMethodB".equals(method.getName())){ return 0;//Callback callbacks[0] }else if("getConcreteMethodA".equals(method.getName())){ return 1;//Callback callbacks[1] }else if("getConcreteMethodFixedValue".equals(method.getName())){ return 2;//Callback callbacks[2] } return 1; } }