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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hongweigg/article/details/83416380

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

要点:

1、需要使用接口类

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

示例代码:

1、接口类

package proxy;

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

2、实现类

package proxy;

public class RealSubject implements Subject {
	@Override
	public void rent() {
		System.out.println("I want to rent my house");
	}

	@Override
	public 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;
	}

	@Override
	public 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

参考:

https://blog.csdn.net/u012033124/article/details/53645727?utm_source=itdadao&utm_medium=referral

猜你喜欢

转载自blog.csdn.net/hongweigg/article/details/83416380