查看InvocationHandler的接口说明
InvocationHandler
is the interface implemented by the invocation handler of a proxy instance.
Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke
method of its invocation handler.
每个代理实例都有一个关联的调用处理程序。当在代理实例上调用某个方法时,将对该方法的位置进行编码并发送到其调用处理程序的invoke方法,这个方法正式我们继承InvocationHandler后重写的方法
。
动态代理类,实现InvocationHandler接口
package com.cowcow;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyIHello implements InvocationHandler{
private Object target;
public Object init(Object object) {
this.target = object;
return Proxy.newProxyInstance(this.target.getClass().getClassLoader(),
this.target.getClass().getInterfaces(), this);//此处this就是DynamicProxyIHello实例,
//每个代理实例都有一个关联的调用处理程序。当在代理实例上调用某个方法时,将对该方法的位置进行编码并发送到其调用处
//理程序的invoke方法
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object result = null;
if (!"sayHi".equals(method.getName())) {
Logger.start();
result = method.invoke(this.target, args);
Logger.end();
} else {
result = method.invoke(this.target, args);
}
return result;
}
}
运行类,用于测试
package com.cowcow;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
IHello iHello = (IHello) new DynamicProxyIHello().init(new Hello());
//ProxyHello proxyHello = new ProxyHello(iHello);
//proxyHello.sayHello();Proxy
iHello.sayHello();//
iHello.sayHi();
//生成的是代理类
System.out.println(iHello instanceof Proxy);
//返回的代理类应该继承了Proxy实现了IHello接口
System.out.println("iHello的class类是: " + iHello.getClass().toString());
Field [] fields = iHello.getClass().getDeclaredFields();
for (Field field : fields) {
System.out.println(field.getName() + ", ");
}
Method [] methods = iHello.getClass().getDeclaredMethods();
for (Method method: methods) {
System.out.println(method.getName() + ", ");
}
System.out.println("iHello的父类是: " + iHello.getClass().getSuperclass());
Class>[] interfaces = iHello.getClass().getInterfaces();
for (Class> i : interfaces) {
System.out.println(i.getName() + ", ");
}
}
}
接口实现类,用于动态代理类的实例化
package com.cowcow;
public class Hello implements IHello {
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Hello World!");
}
@Override
public void sayHi() {
// TODO Auto-generated method stub
System.out.println("Hi world!");
}
}
接口
package com.cowcow;
public interface IHello {
public void sayHello();
public void sayHi();
}
日志类,用于测试动态代理效果
package com.cowcow;
public class Logger {
public static void start() {
System.out.println("logger starting...");
}
public static void end() {
System.out.println("logger ending...");
}
}