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();
}
}
目标类代码如下:
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();
}
}
相关文章推荐
- JDK动态代理为什么必须用接口以及与CGLIB的对比
- JDK动态代理为什么必须针对接口 其与CGLIB的对比
- JDK的动态代理为什么必须要使用接口与使用CGLIB动态代理
- Java动态代理(JDK接口代理和Cglib类代理)
- java动态代理2 (cglib 不用实现接口)
- Spring AOP-有接口的CGLIB动态代理
- 有接口的CGLIB动态代理实现
- 由service层接口有什么用?引申到基于JDK原生和CGLIB动态代理实现spring事务管理的机制的思考
- Spring aop 基于JDK动态代理和CGLIB代理的原理以及为什么JDK代理需要基于接口
- 动态代理不通过接口,CGLIB动态代理
- java动态代理——JDK和CGLIB原理解析与使用
- cglib动态代理介绍(一)
- java动态代理(JDK和cglib)
- Spring—AOP两种代理机制对比(JDK和CGLib动态代理)
- CGLib动态代理原理及实现
- Spring2.5学习4.2_Proxy实现动态代理(目标类实现随意接口)
- Java动态代理之JDK实现和CGlib实现(简单易懂)
- 通过代理接口在内存中动态生成代理类源代码并编译实现的真正动态代理
- JDK动态代理为什么必须用以及与CGLIB的对比