黑马程序员_java高级篇代理Day14(下)

                                                                         


     ----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流! --------    

   

                                     黑马程序员_java高级篇代理Day14(下)


这篇主要是用代码来试看看代理类的实现,以及AOP编程,BeanFactory的应用


#代理类的实现#

package day13;

import java.awt.event.InvocationEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyTest {

	/**
	 * 动态代理的实现
	 */
	public static void main(String[] args) throws SecurityException, Exception {
		// TODO Auto-generated method stub
         
	Class classProxy=Proxy.getProxyClass(Collection.class.getClassLoader(),Collection.class);
	 Constructor[]  constructors  =  classProxy.getConstructors();
	 System.out.println("-----classProxy得到构造开始--------");
	 for(Constructor  constructor: constructors)
	 {
		 String name=constructor.getName();
		 StringBuilder strBd=new StringBuilder(name);
		 strBd.append("(");
		 Class[] classPars=constructor.getParameterTypes();
		 for(Class classPar:classPars)
		 {
			strBd.append(classPar.getName()).append(',');
			 
		 }
		 if(classPars.length!=0&&classPars!=null)
		 strBd.deleteCharAt(strBd.length()-1);
		 strBd.append(")");
		 System.out.println(strBd.toString());
	 }
	 
	 System.out.println("-----method开始--------");
	 Method[]  Methods  = classProxy.getMethods();
	 for(Method  method: Methods)
	 {
		 String name=method.getName();
		 StringBuilder strBd=new StringBuilder(name);
		 strBd.append("(");
		 Class[] classPars=method.getParameterTypes();
		 for(Class classPar:classPars)
		 {
			strBd.append(classPar.getName()).append(',');
			 
		 }
		 if(classPars.length!=0&&classPars!=null)
		 strBd.deleteCharAt(strBd.length()-1);
		 strBd.append(")");
		 System.out.println(strBd.toString());
	 }
	 
	 System.out.println("-----creat object开始--------");
	 //1,构造方法
	 Constructor  constructor  =  classProxy.getConstructor(InvocationHandler.class);
	 class myinvocation implements InvocationHandler
	 {

		public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			// TODO Auto-generated method stub
			return null;
		}
		 
	 }

	 //new 对象
	 Collection c= (Collection) constructor.newInstance(new InvocationHandler(){

		public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			// TODO Auto-generated method stub
			return null;
		}
		 
		 
	 });
	
	  //,当我们程序就到这时,调用方法应注意,当我们调用有返回值得方法时,会报错!
      c.clear();
      
    //内部类要想访问target,必须将其定义为final的
	 final  ArrayList target=new ArrayList();
	 //其实 getProxy是我们重构出来的,这个代码也可以放在这里,只是这样看起来更加好
     Collection c1 = (Collection) getProxy(target,new MyAdviser());
     
     //新建了对象后,我们就可以加了,同时这个对象就是ArrayList
      c1.add("s");
      c1.add("dsd");
      c1.add("ds");
      System.out.println(c1.size());
	}

	public static Object getProxy(final Object target,final Advise advise) {
		Collection c1=(Collection) Proxy.newProxyInstance(/*Collection.class.getClassLoader()*/target.getClass().getClassLoader(),/*new Class[]{Collection.class}*/target.getClass().getInterfaces(),new InvocationHandler(){
			  
			  
				public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			// TODO Auto-generated method stub
					
					advise.beforeMethod(method);
				    //Long startTime=System.currentTimeMillis();
					Object val= method.invoke(target,args);
					advise.afterMethod(method);
					//Long endTime=System.currentTimeMillis();
					
			        return val;
			       
			       
		}
			  
		  });
		return c1;
	}
	}
	
	
	


#中间的接口Advise#

package day13;

import java.lang.reflect.Method;

public interface Advise {

	public void beforeMethod(Method m);
	public void afterMethod(Method m);
}

#实现了Advise接口的类#

package day13;

import java.lang.reflect.Method;

public class MyAdviser implements Advise {



	/**
	 * @param args
	 */
	 long startTime=0;
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public void afterMethod(Method m) {
		// TODO Auto-generated method stub
		Long endTime=System.currentTimeMillis();
		System.out.println(m.getName()+":"+(endTime-startTime));
	}

	public void beforeMethod(Method m) {
		// TODO Auto-generated method stub
		 startTime=System.currentTimeMillis();
	}

}

#使用AOP Bean模仿Spring原理#

#AopTest#

package day13;

import java.io.IOException;
import java.io.InputStream;

public class AopTest {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		InputStream is=AopTest.class.getResource("config.properties").openStream();
                //调用方法
		Object bean=new BeanFactory(is).getBean("xxx");
		System.out.println(bean.getClass().getName());
		
	}

}

#BeanFactory#

这里要判断一下这个对象是否在ProxyFactoryBean中,如果不在直接不执行if,返回对象,如果是一个代理,那就要执行if

package day13;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	Properties prop=new Properties();
	public BeanFactory(InputStream is) throws Exception
	{
		prop.load(is);
	}
	
	public Object getBean(String name) throws Exception
	{
		
		String className=prop.getProperty(name);
		System.out.println("helo"+className);
		Object obj=Class.forName(className).newInstance();
                //这里要判断一下这个对象是否在ProxyFactoryBean中,如果不在直接不执行if,返回对象,如果是一个代理,那就要执行if

		if(obj instanceof ProxyFactoryBean)
		{
			  Object proxy=null;
			ProxyFactoryBean proxyfactoryBean=(ProxyFactoryBean)obj;
			Object target=Class.forName(prop.getProperty(name+".target")).newInstance();
			
			Advise advise=(Advise) Class.forName(prop.getProperty(name+".advise")).newInstance();
			
			proxyfactoryBean.setTarget(target);
			proxyfactoryBean.setAdvise(advise);
	       proxy=((ProxyFactoryBean)obj).getProxy();
	      
			return proxy;
		}
		return obj;
		
		
	}
}

#ProxyFactoryBean#

我老疑惑怎么不要构造方法把那两个参数target,advise传进来,原来他们都是静态的成员变量。

package day13;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;

public class ProxyFactoryBean {

	/**
	 * @param args
	 */
	private static Object target;
	private static Advise advise;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public static Object getProxy() {
		Collection c1=(Collection) Proxy.newProxyInstance(/*Collection.class.getClassLoader()*/target.getClass().getClassLoader(),/*new Class[]{Collection.class}*/target.getClass().getInterfaces(),new InvocationHandler(){
			  
			  
				public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			// TODO Auto-generated method stub
					
					//其实我们是把以前写这里的代码,都抽出来,写到advise里面去了
					advise.beforeMethod(method);
				    //Long startTime=System.currentTimeMillis();
					Object val= method.invoke(target,args);
					advise.afterMethod(method);
					//Long endTime=System.currentTimeMillis();
					
			        return val;
			       
			       
		}
			  
		  });
		return c1;
	}

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public static Advise getAdvise() {
		return advise;
	}

	public static void setAdvise(Advise advise) {
		ProxyFactoryBean.advise = advise;
	}



}



     ----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流! --------    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值