静态代理和动态代理
Posted KevinEngineer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了静态代理和动态代理相关的知识,希望对你有一定的参考价值。
静态代理:
1 package com.company.Proxy; 2 3 public class StaticProxy { 4 public static void main(String[] args) { 5 // write your code here 6 Person student = new Student("张三"); 7 Person monitor = new Monitor(student); 8 monitor.giveMoney(); 9 10 } 11 } 12 13 interface Person{ 14 void giveMoney(); 15 } 16 17 /* 18 被代理类:学生 19 */ 20 class Student implements Person{ 21 22 private String name; 23 24 public Student(String name) { 25 this.name = name; 26 } 27 28 @Override 29 public void giveMoney() { 30 System.out.print(this.name+"上交了50元班费"); 31 } 32 } 33 34 /* 35 代理类:班长 36 */ 37 class Monitor implements Person{ 38 39 private Student student; 40 41 public Monitor(Person student) { 42 this.student = (Student) student; 43 } 44 45 @Override 46 public void giveMoney() { 47 System.out.println("张三第一个交班费"); 48 student.giveMoney(); 49 } 50 }
动态代理:
1 package com.company.Proxy; 2 3 import com.company.util.MonitorUtil; 4 5 import java.lang.reflect.InvocationHandler; 6 import java.lang.reflect.Method; 7 import java.lang.reflect.Proxy; 8 9 public class DynamicProxy { 10 public static void main(String[] args){ 11 Person1 student = new Student1("zhangsan"); 12 InvocationHandler stuHandler = new StuInvocationHandler<Person1>(student); 13 Person1 stuProxy = (Person1) Proxy.newProxyInstance(Person1.class.getClassLoader(),student.getClass().getInterfaces(),stuHandler); 14 stuProxy.giveMoney(); 15 stuProxy.info(); 16 } 17 } 18 19 interface Person1{ 20 void giveMoney(); 21 void info(); 22 } 23 24 class Student1 implements Person1 { 25 private String name; 26 public Student1(String name) { 27 this.name = name; 28 } 29 30 @Override 31 public void giveMoney() { 32 try { 33 //假设数钱花了一秒时间 34 Thread.sleep(1000); 35 } catch (InterruptedException e) { 36 e.printStackTrace(); 37 } 38 System.out.println(name + "上交班费50元"); 39 } 40 41 @Override 42 public void info() { 43 System.out.println("hello"); 44 } 45 } 46 47 class StuInvocationHandler<T> implements InvocationHandler{ 48 49 T target; 50 51 public StuInvocationHandler(T target) { 52 this.target = target; 53 } 54 55 @Override 56 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 57 System.out.println("正在代理"+method.getName()+"方法"); 58 MonitorUtil.start(); 59 Object result = method.invoke(target,args); 60 MonitorUtil.finish(method.getName()); 61 return result; 62 } 63 }
动态代理相比于静态代理的好处是:
当被代理类增加某个方法时,静态代理需要修改代理类,而动态代理可以直接调用新方法。
以上是关于静态代理和动态代理的主要内容,如果未能解决你的问题,请参考以下文章