代理类的使用
JDK 1.3以后,JAVA增加了动态代理类,使用代理类,你可以接管类的方法调用,可以让你在类的方法调用前后,增加功能,比如日志,性能测试,等等。
代理类主要使用java.lang.reflect包下的InvocationHandler接口和Proxy类。首先要实现InvocationHandler接口,该接口有一个方法invoke,代理类通过这个方法调用真正的实现方法,在这个方法中,你可以加入日志输出,性能测试等等的代码。
由于代理类只能代理接口,所以你的真正的实现类要抽出接口,然后通过Proxy类的静态方法newProxyInstance生成代理类,通过调用调用代理类的接口方法完成对代理类所代理的实现类的方法调用。下面的代码通过一个简单的代理类,实现在方法的前后输出日志。
public class MyProxyHandler implements InvocationHandler {
private Object obj;
public MyProxyHandler(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
System.out.println(method.getName() + " start.");
result = method.invoke(obj, args);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
System.out.println(method.getName() + " end.");
}
return result;
}
}
public interface MyBusiness {
public void helloWorld();
public String sayHello(String target);
}
public class MyBusinessImpl implements MyBusiness {
public void helloWorld() {
System.out.println("Hello world!");
}
public String sayHello(String target) {
return "Hello " + target + "!";
}
}
public class MyTestClass {
public static void main(String[] args) {
MyBusiness business = new MyBusinessImpl();
MyBusiness businessProxy =
(MyBusiness) Proxy.newProxyInstance(
business.getClass().getClassLoader(),
business.getClass().getInterfaces(),
new MyProxyHandler(business));
businessProxy.helloWorld();
System.out.println(businessProxy.sayHello("Mr. Pu"));
}
}
Tue 12 Oct | baotuo |