java代理1

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

scrapy按顺序启动多个爬虫代码片段(python3)

Java RMI地址解析问题

java代码在片段活动中不起作用

java 代码片段【JAVA】

# Java 常用代码片段

# Java 常用代码片段