动态代理类实现InvocationHandler接口。在这个类中,需要两个方法。一个是需要新建用来接收对象的方法,在这个方法中,接收这个对象,实现这个对象实现的接口。一个是实现这个invocationhandler接口需要实现的invoke方法,在这个方法中实现你需要在你的程序调用前后进行的事情。
public class helloProxy implements InvocationHandler{
private Object proxyobj;
public helloProxy(Object obj){
this.proxyobj=obj;
}
//接收传来的对象,对象实现什么接口,返回的代理就实现什么接口
public static Object bind(Object obj){
Class clazz=obj.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[]args)
throws Throwable {
// TODO Auto-generated constructor stub 在这里你可以写一些自己想做的事情
System.out.println(“i love you”);
Object object=method.invoke(proxyobj,args);//这句是用来调用原本的程序、原本的方法
//TODO Auto-generated constructor stub 同样,在这里你可以写一些代码,它会在你的原本的方法实现后实现
System.out.println(“i love you too”);
return object;
}
public class helloProxy
private Object proxyobj;
public helloProxy(Object obj){
this.proxyobj=obj;
}
//接收传来的对象,对象实现什么接口,返回的代理就实现什么接口
public static Object bind(Object obj){
Class clazz=obj.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[]args)
throws Throwable {
// TODO Auto-generated constructor stub
System.out.println(“i love you”);
Object object=method.invoke(proxyobj,args);//这句是用来调用原本的程序、原本的方法
//TODO Auto-generated constructor stub
System.out.println(“i love you too”);
return object;
}