实现步骤:
1.创建一个实现接口InvacationHandler的类,它必须实现invoke方法,并添加相应的功能。
package com.imooc.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class TimeHandler implements InvocationHandler {
private Object target;
public TimeHandler(Object target) {
super();
this.target = target;
}
public TimeHandler() {
}
/**
* 参数: proxy 被代理对象 method 被代理对象的方法 arg 方法的参数
*
* 返回值: Object 方法的返回值
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long startTime = System.currentTimeMillis();
System.out.println("汽车开始行驶");
method.invoke(target);
long endTime = System.currentTimeMillis();
System.out.println("汽车结束行驶... 汽车行驶时间:" + (endTime - startTime) + "毫秒");
return null;
}
}
2.创建被代理的类以及接口
接口:
public interface Moveable {
void move();
}
被代理的类:
import java.util.Random;
public class Car implements Moveable {
@Override
public void move() {
// 实现开车
try {
Thread.sleep(new Random().nextInt(1000));
System.out.println("汽车形式中");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.调用Proxy的静态方法,创建一个代理类【Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), h);】并通过代理调用方法。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import com.imooc.proxy.Car;
import com.imooc.proxy.Moveable;
public class Test {
public static void main(String[] args) {
Car car = new Car();
InvocationHandler h = new TimeHandler(car);
Class<?> c = car.getClass();
/**
* loader 类加载器
* interface 实现接口
* h InvocationHandler
*/
Moveable m = (Moveable) Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), h);
/**
*通过代理调用方法
*/
m.move();
}
}
控制台输出:
汽车开始行驶
汽车形式中
汽车结束行驶… 汽车行驶时间:833毫秒