动态代理来做的话如下:
Circle类和GeometryUtils接口不变。- package staticproxy;
- import java.lang.annotation.Target;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import org.junit.Test;
- class Advice{
- public static void before(Object obj){
- System.out.println("代理类服务开始");
- if(obj instanceof Circle)((Circle)obj).setR(2);
- }
- public static void after(){
- System.out.println("代理类服务完成");
- }
- }
- public class MyDynamicProxyTest {
- @Test
- public void test01(){
- GeometryUtils proxy = (GeometryUtils) Proxy.newProxyInstance(GeometryUtils.class.getClassLoader(),
- new Class[]{GeometryUtils.class},
- new InvocationHandler() {
- Circle target = new Circle();
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- // TODO Auto-generated method stub
- Object reval = null;
- Advice.before(target);
- reval = method.invoke(target, null);
- Advice.after();
- return reval;
- }
- });
- proxy.Space();
- }
- }
复制代码 |