动态代理
步骤:1.先创建一个被代理对象的接口和实现类
public interface ArithmeticCalculator {
int add ( int a , int b) ;
int sub ( int a , int b) ;
int mul ( int a , int b) ;
int div ( int a , int b) ;
}
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ 实现类~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
@Component
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
@Override
public int add ( int a, int b) {
int c= a+ b;
return c;
}
@Override
public int sub ( int a, int b) {
int c= a- b;
return c;
}
@Override
public int mul ( int a, int b) {
int c= a* b;
return c;
}
@Override
public int div ( int a, int b) {
int c= a/ b;
return c;
}
}
2.创建代理类
public class MyProxy {
private Object target;
public MyProxy ( Object target) {
this . target = target;
}
public Object getInstance ( ) {
ClassLoader loader = target. getClass ( ) . getClassLoader ( ) ;
Class< ? > [ ] interfaces = target. getClass ( ) . getInterfaces ( ) ;
InvocationHandler h= new InvocationHandler ( ) {
@Override
public Object invoke ( Object proxy, Method method, Object[ ] args) throws Throwable {
System. out. println ( method. getName ( ) + "," + Arrays. asList ( args) ) ;
Object result = method. invoke ( target, args) ;
System. out. println ( method. getName ( ) + "," + result) ;
return result;
}
} ;
return Proxy. newProxyInstance ( loader, interfaces, h) ;
}
}
3.测试
public static void main ( String[ ] args) {
ArithmeticCalculatorImpl arithmeticCalculator = new ArithmeticCalculatorImpl ( ) ;
MyProxy myProxy = new MyProxy ( arithmeticCalculator) ;
ArithmeticCalculator proxyInstance = ( ArithmeticCalculator) myProxy. getInstance ( ) ;
int add = proxyInstance. add ( 10 , 2 ) ;
System. out. println ( add) ;
}
结果 如图