JDk动态代理
1. jdk动态代理通过jdk提供的Proxy类生成代理对象
2. newInstance();
3. 但是只能代理实现类某种接口的, 不能读取类中的注解等信息
4. 不能读取指定的类的信息,
Cour c = new Person();Cour proxyC = (Cour) Proxy.newProxyInstance(c.getClass().getClassLoader(), c.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("我是法官");Object invoke = method.invoke(c, args);return invoke;}});int court = proxyC.Court(111);
System.out.println(court);
Cglib动态代理
1. 解决了不能增强特定类的问题, 能够读取注解
2. 使用了ASM字节码矿建读取字节码文件的生成新的类
3. 通过对方法的拦截,来实现方法增强的实现
4. 通过使用Enhance对象和MethodInterceptro()来对方法进行拦截
`public static void main(String[] args) {Person person = new Person();// 使用cglib创建Enhance对象Enhancer enhancer = new Enhancer();//设置子类的字节码文件enhancer.setSuperclass(person.getClass());/***@描述 用于增强父类中的方法*@参数methodProxy: 子类中的代理的方法*@返回值objects:方法的参数列表*/enhancer.setCallback(new MethodInterceptor() {@Overridepublic Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println("method executer before");Object invokeSuper = methodProxy.invokeSuper(o, objects);System.out.println("method executor after");return invokeSuper;}});//生成代理对象Person o = (Person) enhancer.create();o.eat();}`
Enhancer(中文释义:增强剂)
- 和Proxy对象差不多,既能够代理接口和普通的类都是可以的,不想proxy只能代理接口,
- 通过创建被代理的对象的一个子类对象并且通过拦截所有的方法的调用,不能够拦截Final修饰的方法
- Enhancer同时也不能够操作静态和Final修饰的, 构造方法也是不可以的
- Enhance.create()创建代理对象
`@ Test
public void test1(){//获取增强剂Enhancer en = new Enhancer();en.setSuperclass(SampleClass.class);en.setCallback(new FixedValue() {//FixedValue 用来拦截所有的方法返回相同的值@Overridepublic Object loadObject() throws Exception {return "Hello Cglib";}});SampleClass o = (SampleClass)en.create();System.out.println(o.test("((("));System.out.println(o.toString());}
}
class SampleClass {public String test(String input){return "hello world";}
}`
对指定的方法拦截, 其他的方法放行
`Enhancer enhancer = new Enhancer();
CallbackHelper callbackHelper = new CallbackHelper(SampleClass.class, new Class[0]) {@Overrideprotected Object getCallback(Method method) {if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class){return new FixedValue() {@Overridepublic Object loadObject() throws Exception {return "Hello cglib";}};}else{return NoOp.INSTANCE;}}
};
enhancer.setSuperclass(SampleClass.class);
enhancer.setCallbackFilter(callbackHelper);
enhancer.setCallbacks(callbackHelper.getCallbacks());
SampleClass proxy = (SampleClass) enhancer.create();
Assert.assertEquals("Hello cglib", proxy.test(null));
Assert.assertNotEquals("Hello cglib",proxy.toString());
System.out.println(proxy.hashCode());`
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!