1.代理模式使用到的接口与类
1.1java.lang.reflect
Interface InvocationHandler
Method method, Object[] args) throws Throwable
1.2 java.lang.reflect.Proxy
public class Proxy extends Object implements Serializable
static Object |
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler. |
package com.cc; public interface People { String getName(); void setName(String name); void print(); } package com.cc; public class Man implements People { private String name; @Override public String getName() { // TODO Auto-generated method stub return name; } //@Override public void setName(String name) { // TODO Auto-generated method stub this.name = name; } @Override public void print() { // TODO Auto-generated method stub System.out.println(name); } } package com.cc; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class PeopleProxy implements InvocationHandler { private Object target; public PeopleProxy(){ } public PeopleProxy(Object target){ this.target = target; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } public Object getProxy(){ return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub Object result; System.out.println(proxy instanceof People); System.out.println(method); System.out.println("--start--"); result = method.invoke(target, args); System.out.println("--end--"); return result; } } package com.cc; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub People p = new Man(); PeopleProxy pp = new PeopleProxy(p); People p2 = (People) pp.getProxy(); People p3 = (People) pp.getProxy(); p2.setName("ccc"); System.out.println(p3.getName()); p2.print(); } }
时间: 2024-10-07 02:16:50