您的位置:首页 > 其它

CGLIB无接口动态代理

2018-02-07 15:28 363 查看
需要载入一个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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: