码迷,mamicode.com
首页 > 编程语言 > 详细

java代理1

时间:2016-10-09 13:43:30      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/fengfengtk/p/5941457.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!