jdk动态代理
1目标类接口
public interface shop {
void buy(String name);
}
2目标类
public class USBShop implements shop{
@Override
public void buy(String name) {
System.out.println("卖"+name+"U盘");
}
}
3代理类
```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class invocationImpl implements InvocationHandler {
Object target;
public invocationImpl(Object target) {
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("===进货===");
method.invoke(target,args);
return null;
}
}
4、测试类
import java.lang.reflect.Proxy;
public class mainInvoke {
public static void main(String[] args) throws NoSuchMethodException {
shop usb = new USBShop();
invocationImpl handler = new invocationImpl(usb);
shop proxy =(shop)Proxy.newProxyInstance(usb.getClass().getClassLoader(), usb.getClass().getInterfaces(), handler);
//invocationImpl invocation = new invocationImpl(target);
proxy.buy("金士顿");
}
}
结果