1.接口类与实现类
package dynamic;
public interface ICalculator {
Integer add(Integer i,Integer j);
Integer sub(Integer i,Integer j);
}
package dynamic;
public class Calculator implements ICalculator {
//加法
public Integer add(Integer i,Integer j){
Integer result =i+j;
return result;
}
//减法
public Integer sub(Integer i,Integer j){
Integer result =i-j;
return result;
}
}
2.MyInvocationHandler类
package dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
public class MyInvocationHandler implements InvocationHandler {
Object target;
public MyInvocationHandler(Object target){
this.target = target;
}
@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("方法的执行结果是" + result);
return result;
}
}
3.测试类
import dynamic.Calculator;
import dynamic.ICalculator;
import dynamic.MyInvocationHandler;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class MainTest {
ClassLoader loader=ICalculator.class.getClassLoader();
Class<?>[] interfaces=new Class[]{ICalculator.class};
InvocationHandler handler=new MyInvocationHandler(new Calculator());
/*
* 使用jdk动态代理
* */
@Test
public void test(){
ICalculator o = (ICalculator)Proxy.newProxyInstance(loader, interfaces, handler);
System.out.println(o.getClass());
o.add(1, 1);
o.sub(9,3);
}
}