java 基础 动态代理

匿名 (未验证) 提交于 2019-12-02 21:52:03
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完成
之前做一些事
吃之前跑下步

之后做一些事

 

动态代理

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!