700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java动态代理一个浅显易懂的例子

Java动态代理一个浅显易懂的例子

时间:2021-04-03 09:58:12

相关推荐

Java动态代理一个浅显易懂的例子

简单用途,在不修改一个类的前提下,在该类的方法执行前或执行后加入一些特殊的处理,如日志、事务等。

要点:

1、需要使用接口类

2、使用动态代理在方法调用时加入自己的处理

示例代码:

1、接口类

package proxy;public interface Subject {public void rent();public void hello(String str);}

2、实现类

package proxy;public class RealSubject implements Subject {@Overridepublic void rent() {System.out.println("I want to rent my house");}@Overridepublic void hello(String str) {System.out.println("hello: " + str);}}

3、动态代理类

package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class DynamicProxy implements InvocationHandler {// 这个就是我们要代理的真实对象private Object subject;// 构造方法,给我们要代理的真实对象赋初值public DynamicProxy(Object subject) {this.subject = subject;}@Overridepublic Object invoke(Object object, Method method, Object[] args) throws Throwable {System.out.println("\r\nMethod:" + method);// 在代理真实对象前我们可以添加一些自己的操作System.out.println("before invoke method " + method.getName()); // 当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用method.invoke(subject, args);// 在代理真实对象后我们也可以添加一些自己的操作System.out.println("after invoke method " + method.getName());return null;}}

4、应用类

package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;public class Client {public static void main(String[] args) {// 我们要代理的真实对象Subject realSubject = new RealSubject();// 我们要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法的InvocationHandler handler = new DynamicProxy(realSubject);/** 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数 第一个参数* handler.getClass().getClassLoader()* ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象* 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口* ,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了 第三个参数handler, 我们这里将这个代理对象关联到了上方的* InvocationHandler 这个对象上*/Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),realSubject.getClass().getInterfaces(), handler);System.out.println(subject.getClass().getName());subject.rent();subject.hello("world");}}

输出结果:

com.sun.proxy.$Proxy0

Method:public abstract void proxy.Subject.rent()

before invoke method rent

I want to rent my house

after invoke method rent

Method:public abstract void proxy.Subject.hello(java.lang.String)

before invoke method hello

hello: world

after invoke method hello

参考:

/u012033124/article/details/53645727?utm_source=itdadao&utm_medium=referral

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。