需要载入一个jar包 cglib.jar 包
目标类代码如下:
package com.sxjyatc.CGLIB;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class H implements MethodInterceptor {
private G g;
public H() {
super();
// TODO Auto-generated constructor stub
}
public H(G g) {
super();
this.g = g;
}
public G myG(){
Enhancer enhancer = new Enhancer();
//指定父类,即目标类。 因为cglib原理 子类增强父类
enhancer.setSuperclass(G.class);
//设置回掉接口.
enhancer.setCallback(this);
return (G)enhancer.create();
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
Object o=arg1.invoke(g, arg2);
if(o!=null){
return ((String)o).toUpperCase();
}
return null;
}
}
Test测试:
package com.sxjyatc.CGLIB;
/**
* @author 86497
*
*/
public class Mytest {
public static void main(String[] args) {
G g = new G();
G h = new H(g).myG();
System.out.println(h.first());
h.second();
}
}