首页 > 代码库 > java代理1
java代理1
1.代理模式使用到的接口与类
1.1java.lang.reflect
Interface InvocationHandler
Object invoke(Object proxy,
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(); }}
java代理1
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。