总共四个类,一个接口类、一个接口实现类、一个动态代理类、一个测试类。
接口类:
package com.qw.spring;
public interface AtithmeticCalculator {
int add(int i,int j);
int sub(int i,int j);
}
接口实现类:
package com.qw.spring;
public class AtithmeticCalculatorImpl implements AtithmeticCalculator {
@Override
public int add(int i, int j) {
int result = i + j;
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
return result;
}
}
动态代理类:
package com.qw.spring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ArithmeticCalculatorLoggingProxy {
//要代理的对象
private AtithmeticCalculator target;
public ArithmeticCalculatorLoggingProxy(AtithmeticCalculator target){
this.target = target;
}
public AtithmeticCalculator getlLoggingProxy(){
AtithmeticCalculator proxy = null;
//代理对象由哪一个类加载器负责加载
ClassLoader loader = target.getClass().getClassLoader();
//代理对象的类型,即其中有哪些方法
Class[] interfaces = new Class[]{AtithmeticCalculator.class};
//当调用代理对象其中的方法是,该执行的代码
InvocationHandler h = new InvocationHandler() {
/**
* proxy:正在返回的那个代理对象,一般情况下,在invoke方法中都不使用该对象。
* method:正在被调用的方法
* args:调用方法时,传入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("被调用的方法名:"+method.getName());
//执行的方法
Object result = method.invoke(target, args);
return result;
}
};
proxy = (AtithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}
测试类:
package com.qw.spring;
public class Main {
public static void main(String[] args) {
AtithmeticCalculator target = new AtithmeticCalculatorImpl();
AtithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getlLoggingProxy();
int result = proxy.add(1, 2);
System.out.println(result);
}
}