本文出自“”,转载请务必保留此出处.
代理: 对某一对象提供代理对象,由代理对象控制该对象的引用.
静态代理: 对象和代理对象都应实现统一接口
动态代理: 代理对象实现InvocationHandler接口
动态代理相关类:
java.lang.reflect.Proxy
java.lang.reflect.InvocationHandler
java.lang.reflect.Method
定义一个统一接口
public interface UserInterface { public String getName(); public String getAddress();}
实现类:
public class Chenhaitao implements UserInterface { public String getName(){ return "chenhaitao"; } public String getAddress(){ return "beijing"; }}
代理类:
public ChenhaitaoProxy implements InvocationHandler { private UserInterface userInterface; public void ChenhaitaoProxy (UserInterface userInterface){ this.userInterface=userInterface; } public UserInterface getUserInterface (){ return (UserInterface) Proxy.newProxyInstance(UserInterface.class.getClassLoader, new Class[]{ UserInterface.class }, this ); } @Override public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{ if(method.getName().equals("getAddress")){ return this.getAddress(); }else{ return method.invoke(myinterface, args); } } public String getAddress(){ return "www.chenhaitao1981.com"; }}
使用:
public static void main(String[] args){ ChenhaitaoProxy proxy=new ChenhaitaoProxy(new Chanhaitao()); UserInterface userInterface =proxy.getUserInterface(); userInterface.getName(); // chenhaitao userInterface.getAddress(); // www.chenhaitao1981.com}