简单的代理-jdk代理
1 申明一个接口
public interface JdkProxyDemo{
void sayHi(String name);
}
2 实现这个接口
public class JdkProxyDemoImpl implements JdkProxyDemo {
@Override
public void sayHi(String name) {
System.out.println("hello " + name);
}
}
3 实现InvocationHandler接口完成代理功能
public class JdkProxyDemoHandler implements InvocationHandler {
//真实的对象
private Object target;
//返回的服务代理对象
public Object bind(Object target){
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader()
,target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("start-----------");
Object invoke = method.invoke(target, args);
System.out.println("end-------------");
return invoke;
}
public static void main(String[] args) {
JdkProxyDemoHandler jdkProxyDemoHandler =new JdkProxyDemoHandler();
JdkProxyDemo jdkProxyDemo = (JdkProxyDemo) jdkProxyDemoHandler.bind(new JdkProxyDemoImpl());
jdkProxyDemo.sayHi("jj");
}
}