接口:
/**
* 人
*/
public interface Person {
/**
* 吃饭
*/
void eat();
}
实现类:
/**
* 男人
*/
public class Man implements Person {
/**
* 吃饭
*/
public void eat() {
System.out.println("eat()-吃饭");
}
}
自定义InvocationHandler:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 自定义InvocationHandler
*/
public class MyInvocationHandler implements InvocationHandler {
/**
* 目标对象
*/
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
/**
* 执行目标对象的方法
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("饭前洗手");// 此处可以添加java代码,由于演示,使用打印比较直观。
Object result = method.invoke(target, args);
System.out.println("饭后涑口");
return result;
}
/**
* 获取目标对象的代理类
*/
public Object getProxy() {
/**
* 第一个参数:类加载器
* 第二个参数:目标对象的接口集合
* 第三个参数:InvocationHandler类型的对象,
* 此方法(this)是MyInvocationHandler对象。
*/
return Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), target.getClass()
.getInterfaces(), this);
}
}
测试类:
/**
* 测试类
*/
public class Test {
public static void main(String[] args) {
// 创建男人类
Man man = new Man();
// 设置为目标对象
MyInvocationHandler handler = new MyInvocationHandler(man);
// 获取代理
Person proxy = (Person)handler.getProxy();
// 执行方法
proxy.eat();
}
}
由于用本子记录代码实在是太丑,将代码记录在博客里。
相关博客:
http://www.blogjava.net/hello-yun/archive/2014/09/28/418365.html
https://blog.youkuaiyun.com/do_bset_yourself/article/details/51179896