目录
写一个类
package Proxy;
public class Son implements IWork{
public void work(){
System.out.println("儿子你在工作");
}
}
写一个接口,让Son类实现接口
package Proxy;
public interface IWork {
public void work();
}
写一个代理类,代理Son
package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyWork {
public static void main(String[] args) {
IWork son = new Son();
IWork o = (IWork) Proxy.newProxyInstance(son.getClass().getClassLoader(), son.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("父亲我帮你看合同");
method.invoke(son, args);
System.out.println("父亲我帮你拿工资");
return null;
}
});
o.work();
}
}
效果
没有用代理
package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyWork {
public static void main(String[] args) {
IWork son = new Son();
IWork o = (IWork) Proxy.newProxyInstance(son.getClass().getClassLoader(), son.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("父亲我帮你看合同");
method.invoke(son, args);
System.out.println("父亲我帮你拿工资");
return null;
}
});
// o.work();
son.work();
}
}
效果



