package com.jd.calculator;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.jd.calculator.CalculatorService;
import com.jd.calculator.ICalculatorService;
public class Test {
CalculatorService calculatorService;
public Test(CalculatorService calculatorService) {
this.calculatorService = calculatorService;
}
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(proxy.getClass().getName());
System.out.println(method.getDeclaringClass().getName());
String name = method.getName();
System.out.println(this.getClass().getName()+":The "+name+" method begins.");
System.out.println(this.getClass().getName()+":Parameters of the "+name+" method: ["+args[0]+","+args[1]+"]");
Object result = method.invoke(calculatorService, args);//目标方法
System.out.println(this.getClass().getName()+":Result of the "+name+" method:"+result);
System.out.println(this.getClass().getName()+":The "+name+" method ends.");
return result;
}
};
public Object get() {
return Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[] {ICalculatorService.class}, h);//产生一个动态class类,
}
public static void main(String[] args) {
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
Test test = new Test(new CalculatorService());
ICalculatorService calculatorService = (ICalculatorService) test.get();//获取代理对象
System.out.println(calculatorService.getClass().getName());
int result = calculatorService.add(1, 1);
System.out.println("-->"+result);
}
}
首先看main方法:第一行代码
“System.getProperties().put(“sun.misc.ProxyGenerator.saveGeneratedFiles”, “true”);”作用是把产生的动态Class类的class文件编译出来,方便我们反编译它来观察产生的动态类。
第二行代码 给成员变量赋值
第三行代码 test.get()调用get方法,该方法产生动态Class类
newProxyInstance方法源代码如下:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{