zoukankan      html  css  js  c++  java
  • java 基础 动态代理


    package proxy; public interface human { public void run(); public void eat(); }

      定义接口

    以接口完成类的定义

    package proxy;
    
    public class teacher implements human{
    
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		System.out.println("走");
    	}
    
    	@Override
    	public void eat() {
    		// TODO Auto-generated method stub
    		System.out.println("吃");
    	}
    
    }
    

     

    完成主函数的定义

    package proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    import org.junit.Test;
    
    public class demo {
    	public static void main(String[] args) {
    		teacher teacher1 = new teacher();
    		
    		human teacher2 = (human) Proxy.newProxyInstance(teacher.class.getClassLoader(),teacher.class.getInterfaces() , new InvocationHandler() {
    
    			
    			/*invoke代表的执行代理对象的方法                method     对象的方法               args 对象响应的参数*/
    			@Override
    			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    				System.out.println("之前做一些事");
    				if(method.getName().equals("eat")) {    /*判断方法*/
    					System.out.println("吃之前跑下步");
    				}
    				
    				//执行目标对象的方法       
    				Object invokea = method.invoke(new teacher(), args);
    				System.out.println("之后做一些事");
    				// TODO Auto-generated method stub
    				return invokea;
    			}
    		});
    		
    		
    		teacher1.eat();
    		teacher1.run();
    		System.out.println("老师1完成");
    		teacher2.eat();
    		teacher1.run();
    		
    	}
    }
    

      结果



    老师1完成
    之前做一些事
    吃之前跑下步

    之后做一些事

    动态代理

      可以在运行的时候才切入改变类的方法,而不需要预先定义它。

  • 相关阅读:
    POJ 3140 Contestants Division (树形DP,简单)
    POJ 2378 Tree Cutting (树的重心,微变形)
    js数据类型--对象&数组
    关于JS call apply 对象、对象实例、prototype、Constructor、__proto__
    JS模块化编程(四)--require应用
    JS模块化编程(三)
    利用VS正则替换删除文本行首数据等字符
    JS模块化编程(二)
    JS模块化编程(一)
    js继承
  • 原文地址:https://www.cnblogs.com/hywhyme/p/11618895.html
Copyright © 2011-2022 走看看