1.创建一个接口 public interface JDKEntryInterface { void exercise(); } 2.创建一个需要被代理的对象,对象实现 JDKEntryInterface public class JDKEntry implements JDKEntryInterface { private String name; public JDKEntry(String name){ this.name = name; } @Override public void exercise() { System.out.println("my name is " + name + ". I want to exercise"); } } 3.创建 invoactionHandler 对象,该对象有一个Object属性,用于接收需要被代理的真实对象, 该接口作为代理实列的调用处理类 import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class JDKInvocationHandler implements InvocationHandler { private Object object; public void setObject(Object object) { this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("---------执行前动作-----------"); Object result = method.invoke(this.object, args); System.out.println("---------执行后动作-----------"); return result; } } 4.创建需要被代理的对象,将该对象传入 invocationHandler中 JDKEntryInterface entry = new JDKEntry("LiXiaolong"); InvocationHandler handler = new JDKInvocationHandler(); ((JDKInvocationHandler) handler).setObject(entry); 5.使用Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)返回一个Class类型的代理类,在参数中需要提供类加载器并需要指定代理的接口数组(与真实代理对象实现的接口列表一致) JDKEntryInterface proxy = (JDKEntryInterface) Proxy.newProxyInstance( JDKEntryInterface.class.getClassLoader(), new Class[]{ JDKEntryInterface.class }, handler );
6.执行方法
proxy.exercise();
执行结果:
---------执行前动作----------- my name is LiXiaolong. I want to exercise ---------执行后动作-----------
转载于:https://www.cnblogs.com/www-123456/p/11354792.html
